• Resolved Guido

    (@guido07111975)


    Hi folks,

    My theme has 2 custom page templates and I want to add a meta box on those to page templates only.

    I’m using add_meta_box to create a nice meta box:

    function my_metabox() {
    	add_meta_box(
    		'my-custom-metabox',
    		__( 'My metabox', 'text-domain' ),
    		'my_metabox_callback',
    		'page',
    		'side',
    		'default'
    	);
    }
    add_action( 'add_meta_boxes', 'my_metabox' );

    But now it’s displayed on all pages.
    How do I display it on my 2 custom page templates only?

    Guido

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    Hi Guido,

    First of all, let’s change the hook from ‘add_meta_boxes’ to ‘add_meta_boxes_page’. This fires only for pages so is tad more efficient. This action passes the current WP_Post object as a parameter, so modify your callback to pick that up. my_metabox( $post )

    With the post object you can get the ID as $post->ID. With that you can get the template used from postmeta under ‘_wp_page_template’. See if that’s a match to one of your two templates and only then do you call add_meta_box().

    Thread Starter Guido

    (@guido07111975)

    Hi guys,

    Thanks. Seems kind of difficult to me..
    So I decided to hook this into the Customizer. WP theme review team prefers this as well (using Customizer for theme options).

    Guido

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Metabox on certain custom page templates only’ is closed to new replies.