每个页面和帖子的自定义背景

时间:2018-02-08 作者:WiTon Nope

我创建了一个自定义的后台元数据库,可以在多种帖子类型和帖子上调用它。我有两个问题需要你的帮助。

也可以包括自定义分类法和帖子类别

  • 下面的代码显示了一个旧的时尚颜色选择器和图像上传器,我试图修改它以获得一个新版本,但没有工作,代码如下:

    /**
     * Generate Wordpress Metabox
     */
    class Contentt_Meta_Box {
        private $screens = array(
            \'post\', \'page\', \'sp_event\', \'scoreboard\', \'sp_event\', \'sp_team\', \'sp_player\', \'sp_staff\', \'sp_official\',
        );
        private $fields = array(
            array(
                \'id\' => \'background-color\',
                \'label\' => \'Background Color\',
                \'type\' => \'color\',
                // \'desc\' => esc_html__( \'Choose the background color\', \'Contentt\' ),
                \'class\' => \'button wp-color-result\',
                \'default\'=> \'\',
                \'rgba\' => true,
            ),
            array(
                \'id\' => \'background-image\',
                \'label\' => \'Background Image\',
                \'type\' => \'media\',
                \'class\' => \'images-field clearfix\',
                \'field\' => \'single\'
            ),
            array(
                \'id\' => \'background-repeat\',
                \'label\' => \'Background Repeat\',
                \'type\' => \'select\',
                \'options\' => array(
                    \'no-repeat\' => \'No Repeat\',
                    \'repeat\' => \'Repeat\',
                    \'repeat-x\' => \'Repeat X\',
                    \'repeat-y\' => \'Repeat Y\',
                ),
                \'class\' => \'select-field csfield\',                  
            ),
            array(
                \'id\' => \'background-size\',
                \'label\' => \'Background Size\',
                \'type\' => \'select\',
                \'options\' => array(
                    \'cover\' => \'Cover\',
                    \'auto\' => \'Auto\',
                    \'contain\' => \'Contain\',
                    \'initial\' => \'Initial\',
                ),
                \'class\' => \'select-field csfield\',
            ),
            array(
                \'id\' => \'background-attachment\',
                \'label\' => \'Background Attachment\',
                \'type\' => \'select\',
                \'options\' => array(
                    \'fixed\' => \'Fixed\',         
                    \'scroll\' => \'Scroll\',
                    \'local\' => \'Local\',
                    \'initial\' => \'Initial\',
                    \'inherit\' => \'Inherit\',
                ),
                \'class\' => \'select-field csfield\',
            ),
            array(
                \'id\' => \'background-position\',
                \'label\' => \'Background Position\',
                \'type\' => \'select\',
                \'options\' => array(
                    \'left top\' => \'Left Top\',
                    \'left center\' => \'Left Center\',
                    \'left bottom\' => \'Left Bottom\',
                    \'right top\' => \'Right Top\',
                    \'right center\' => \'Right Center\',
                    \'right bottom\' => \'Right Bottom\',
                    \'center top\' => \'Center Top\',
                    \'center center\' => \'Center Center\',
                    \'center bottom\' => \'Center Bottom\',
                    \'initial\' => \'Initial\',
                ),
                \'class\' => \'select-field csfield\',
            ),
            array(
                \'id\' => \'background-class\',
                \'label\' => \'Background Class\',
                \'type\' => \'text\',
            ),
        );
    
        /**
         * Class construct method. Adds actions to their respective WordPress hooks.
         */
        public function __construct() {
            add_action( \'add_meta_boxes\', array( $this, \'add_meta_boxes\' ) );
            add_action( \'admin_footer\', array( $this, \'admin_footer\' ) );
            add_action( \'save_post\', array( $this, \'save_post\' ) );
            // add_action(\'admin_enqueue_scripts\', array($this, \'admin_script_loader\'));
        }
    
    
        function admin_script_loader() {
            global $pagenow;
            if (is_admin() && ($pagenow==\'post-new.php\' || $pagenow==\'post.php\')) {
                wp_enqueue_style(\'fs-metabox\', get_template_directory_uri() .\'/includes/assets/css/metabox.css\');
                wp_enqueue_media();
                wp_enqueue_script(\'meta-box\', get_template_directory_uri() .\'/includes/assets/js/meta.box.js\');
            }
        }
    
        /**
         * Hooks into WordPress\' add_meta_boxes function.
         * Goes through screens (post types) and adds the meta box.
         */
        public function add_meta_boxes() {
            foreach ( $this->screens as $screen ) {
                add_meta_box(
                    \'background\',
                    __( \'Background\', \'Contentt\' ),
                    array( $this, \'add_meta_box_callback\' ),
                    $screen,
                    \'advanced\',
                    \'default\'
                );
            }
        }
    
        /**
         * Generates the HTML for the meta box
         * 
         * @param object $post WordPress post object
         */
        public function add_meta_box_callback( $post ) {
            wp_nonce_field( \'background_data\', \'background_nonce\' );
            $this->generate_fields( $post );
        }
    
        /**
         * Hooks into WordPress\' admin_footer function.
         * Adds scripts for media uploader.
         */
        public function admin_footer() {
            ?>
      <script type="text/javascript">
        /*
         * Attaches the image uploader to the input field
         */
        jQuery(document).ready(function($){
    
            // Instantiates the variable that holds the media library frame.
            var background_image_frame;
    
            // Runs when the image button is clicked.
            $(\'.fs-metabox-media\').click(function(e){
    
                // Prevents the default action from occuring.
                e.preventDefault();
    
                // If the frame already exists, re-open it.
                if ( background_image_frame ) {
                    background_image_frame.open();
                    return;
                }
    
                // Sets up the media library frame
                background_image_frame = wp.media.frames.background_image_frame = wp.media({
                    title: \'<?php _e( \'Background selection\', \'Contentt\' )?>\',
                    button: { text: \'<?php _e( \'Pick background image\', \'Contentt\' )?>\' },
                    library: { type: \'image\' }
                });
    
                // Runs when an image is selected.
                background_image_frame.on(\'select\', function(){
    
                    // Grabs the attachment selection and creates a JSON representation of the model.
                    var media_attachment = background_image_frame.state().get(\'selection\').first().toJSON();
    
                    // Sends the attachment URL to our custom image input field.
                    $(\'#background-image\').val(media_attachment.url);
    
                    // Sets the preview image to the same value
                    $(\'#background-image-preview\').attr(\'src\', media_attachment.url);
                });
    
                // Opens the media library frame.
                background_image_frame.open();
            });
    
    
            // Removing video embed
            $(".remove-value").click(function() {
                $(this).closest("fieldset").hide().siblings(".value-adder").show().siblings(".value-field").find("input").val(null);
                return false;
            });
    
        });
      </script>
    
    <?php
        }
    
        /**
         * Generates the field\'s HTML for the meta box.
         */
        public function generate_fields( $post ) {
            $output = \'\';
            foreach ( $this->fields as $field ) {
                $label = \'<label class="field-title" for="\' . $field[\'id\'] . \'">\' . $field[\'label\'] . \'</label>\';
                $db_value = get_post_meta( $post->ID, \'background_\' . $field[\'id\'], true );
                switch ( $field[\'type\'] ) {
                    case \'media\':
                        $input = sprintf(
                            \'<input class="regular-text" id="%s" name="%s" type="text" value="%s"> <img src="%s" class="attachment-post-thumbnail size-post-thumbnail" alt="" id="background-image-preview" ><input class="button fs-metabox-media" id="%s_button" name="%s_button" type="button" value="Upload" />\',
                            $field[\'id\'],
                            $field[\'id\'],
                            $field[\'id\'],
                            $db_value,
                            $field[\'id\'],
                            $field[\'id\']
                        );
                        break;
                    case \'select\':
                        $input = sprintf(
                            \'<select id="%s" name="%s">\',
                            $field[\'id\'],
                            $field[\'id\']
                        );
                        foreach ( $field[\'options\'] as $key => $value ) {
                            $field_value = !is_numeric( $key ) ? $key : $value;
                            $input .= sprintf(
                                \'<option %s value="%s">%s</option>\',
                                $db_value === $field_value ? \'selected\' : \'\',
                                $field_value,
                                $value
                            );
                        }
                        $input .= \'</select>\';
                        break;
                    default:
                        $input = sprintf(
                            \'<input %s id="%s" name="%s" type="%s" value="%s">\',
                            $field[\'type\'] !== \'color\' ? \'class="regular-text"\' : \'\',
                            $field[\'id\'],
                            $field[\'id\'],
                            $field[\'type\'],
                            $db_value
                        );
                }
                $output .= $this->row_format( $label, $input );
            }
            echo \'<table class="form-table"><tbody>\' . $output . \'</tbody></table>\';
        }
    
        /**
         * Generates the HTML for table rows.
         */
        public function row_format( $label, $input ) {
            return sprintf(
                \'<tr><th scope="row">%s</th><td>%s</td></tr>\',
                $label,
                $input
            );
        }
        /**
         * Hooks into WordPress\' save_post function
         */
        public function save_post( $post_id ) {
            if ( ! isset( $_POST[\'background_nonce\'] ) )
                return $post_id;
    
            $nonce = $_POST[\'background_nonce\'];
            if ( !wp_verify_nonce( $nonce, \'background_data\' ) )
                return $post_id;
    
            if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE )
                return $post_id;
    
            foreach ( $this->fields as $field ) {
                if ( isset( $_POST[ $field[\'id\'] ] ) ) {
                    switch ( $field[\'type\'] ) {
                        case \'email\':
                            $_POST[ $field[\'id\'] ] = sanitize_email( $_POST[ $field[\'id\'] ] );
                            break;
                        case \'text\':
                            $_POST[ $field[\'id\'] ] = sanitize_text_field( $_POST[ $field[\'id\'] ] );
                            break;
                    }
                    update_post_meta( $post_id, \'background_\' . $field[\'id\'], $_POST[ $field[\'id\'] ] );
                } else if ( $field[\'type\'] === \'checkbox\' ) {
                    update_post_meta( $post_id, \'background_\' . $field[\'id\'], \'0\' );
                }
            }
        }
    }
    new Contentt_Meta_Box;
    
    如下图所示:

    enter image description here

  • 1 个回复
    SO网友:Maxim Sarandi

    用你需要的元字段创建元框。图像字段用于背景图像,文本字段用于其他字段。对于颜色字段,还可以包含jquery颜色选择器。如果你还没有使用WordPress metabox API的经验,我可以推荐使用高级自定义字段插件。解决您发现的问题-这是一个不错的例子。完成在找到的解决方案中编码的所有任务。

    结束

    相关推荐

    Get images by category

    我目前获取滑块图像的方法是使用以下工作正常的代码:$args = array( \'post_type\' => \'attachment\', \'sort_order\' => \'ASC\', \'sort_column\' => \'menu_order\', ); $attachments = get_posts($args); if ($attachments) { $