0

我正在添加媒体弹出屏幕中创建一个复选框,以便在插入图像时将 HTML 添加到 $html 输出。

这工作正常。但是,一旦我添加了选中复选框的图像。如果我尝试再次添加它并取消选中该复选框,它将不会注册或保存更改。

因此,一旦未选中,始终输出修改后的图像,而不是恢复为 WP 默认值。

加上我选择它并插入页面后的复选标记,每次我选择该图像时都会保持预选状态。

如何按预期使取消选择复选框功能?

非常感谢您的帮助。谢谢

class media_uploader_cb{

    function __construct(){
        // attach our function to the correct hook
        add_filter('attachment_fields_to_edit',  array( $this, 'attachment_fields_to_edit' ), 10, 2);
        //save attachment field
        add_filter( 'attachment_fields_to_save', array( $this, 'attachment_fields_to_save' ), 10, 2);
        //add custom css class
        add_filter( 'media_send_to_editor',      array( $this, 'media_send_to_editor' ), 10, 2 );
    }

    /**
     * Adding our custom checkbox field to the $form_fields array
     * 
     * @param array $form_fields
     * @param object $post
     * @return array
     */
    function attachment_fields_to_edit($form_fields, $post) {
        $form_fields['add_class']['label'] = __("Add SEO Data");
        $form_fields['add_class']['input'] = 'html';
        $form_fields['add_class']['html'] = '<input type="checkbox" value="1" name="attachments['.$post->ID.'][add_class]" id="attachments['.$post->ID.'][add_class]" '.checked( 1, get_post_meta($post->ID, 'add_class', true), false ).'/>';
        return $form_fields;
    }


    /**
     * Saving our custom checkbox field
     * @param array $post
     * @param array $attachment
     * @return array
     */
    function attachment_fields_to_save($post, $attachment) {

        if( isset($attachment['add_class']) ){
            update_post_meta($post['ID'], 'add_class', $attachment['add_class']);
        }
        return $post;
    }

    /**
     * Adding our custom css class based on checkbox field 
     * 
     * @param string  $html
     * @param int $id
     * @return string
     */
    function media_send_to_editor( $html, $id ) {
        //only add class if the checkbox was checked
        if ( 1 == (int)get_post_meta($id, 'add_class', true) ){
            //change this to whatever you want
            $seo_data_to_add = 'custom="HTML Output Here""';

            // THIS SHOULD BE THE CHECKBOX
            get_post_meta($id, 'add_class', true);

            $attachment_title = get_the_title($id);
            $title = 'title="'.$attachment_title .' by '. get_option('ews_opt_branding') .'"';
            $html = str_replace('<img', '<img '.$title.' '.$seo_data_to_add.'', $html);
        }
        return $html;
    }


}

new media_uploader_cb();
4

1 回答 1

0

从另一个论坛获得了一些帮助。它在办公室引发了一些头脑风暴,我们想出了一个解决方案。不确定这是否是解决它的最佳方法,但它按预期工作。我添加了这段代码:

delete_post_meta($id, 'add_class', true);

就在上面:

return $html;

在最后一个函数结束时,一切正常。如果有更好的解决方案,请告诉我。

于 2017-09-20T16:10:15.510 回答