How to make WordPress meta boxes specific to a pag

2019-08-06 02:14发布

问题:

Below is some code I have for meta boxes, is there any specific way to limit this to a single page template like template-servicesinner.php or page-plain.php?

$prefix = 'tga_';

$meta_boxes[] = array(
'id' => 'project-box-1',    // meta box id, unique per meta box
'title' => 'Project Box 1', // meta box title
'pages' => array('page'),   // post types, accept custom post types as well, default is     array('post'); optional
'context' => 'normal',      // where the meta box appear: normal     (default), advanced, side; optional
'priority' => 'high',       // order of meta box: high (default), low; optional
'fields' => array(
    array(
        'name' => 'Review thumbnail',
        'desc' => 'Only insert a thumbnail for you review here if you are showing reviews on the homepage (thumbnail should be at least 600x300px). Insert full path to the image, eg. http://yoursite.com/thethumb.jpg',
        'id' => $prefix . 'review_thumb',
        'type' => 'text',
        'std' => ''
    ),

回答1:

The hiding/showing of the metabox requires selecting 'Update' after changing the drop-down field.

function add_meta_box() {
    global $post;
    if(!empty($post)) {
        $pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);

        if($pageTemplate == 'your-page-template-here.php' ) {
            add_meta_box( $id, $title, $callback, 'page', $context, $priority, $callback_args );
        }
    }
}
add_action( 'add_meta_boxes', 'add_meta_box' );

Just update lines 6 and 7 as desired.



回答2:

Yes, there is. And the most user friendly way is done with jQuery. You'll have to listen to changes in the dropdown #page_template. And make the same function run at page load, if template == something, show/hide the meta box.

The scripts are loaded with wp_footer-$hook or admin_print_scripts-$hook. It has been covered in the following Wordpress Answers:

  • Custom meta box shown when template is chosen

  • Toggle admin metabox based upon chosen page template



标签: php wordpress