1

I have created custom page template. Now I have to make it configurable, however since I am using more than one template in my theme I would like to make sure that configuration will be available only when the user chooses this template for a page. Is there an option to do so?

add_meta_box accepts different $post_type, so the closest I can get is to add metabox to all pages, which I would like to avoid.

1
<?
// Check:
// 1. If you are editing post, CPT, or page
// 2. If post type IS NOT SET
if( 'post.php' == basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']) && !isset($_GET['post_type']) ) {

    // get post ID
    $postid = $_GET['post']; 

    // check the template file name
    if ('my_template.php' == get_page_template_slug($postid) ) {
        // add your metabox here
        add_action( 'add_meta_boxes', 'my_metabox' );
    }

}

I don't remember why I was checking post type, not post ID, but you can change

!isset($_GET['post_type'])

to check if post ID is set:

isset($_GET['post'])

Note: meta box will be available only after you save your post (page) using appropriate template.

  • I thought about that but, why would you do 2 checks instead of simple: if (is_page_template( 'my-template.php' )) ?? I wasn't sure what will be impact on performance in that case – Dawid Adach Jul 11 '16 at 20:15
  • I wasn't aware of the function you are talking about. But my function in the answer is Loop-proof, so it works anywhere outside of the Loop. – Max Yudin Jul 12 '16 at 7:37
0

"available only when user choose this template" ? I'm not sure (I doubt it) if this is even possible. Instead I would suggest either of the following two options:

If you want to make the page template configurable on a per-page basis then meta boxes could be the right direction. You could for example add an option like "use featured image as background" or the like…

If however you would like to make your page template configurable on a more general basis, you could use Theme Options instead. Here's an introduction in the codex: https://codex.wordpress.org/Creating_Options_Pages

  • Thanks, my point is that I have very specific configuration for this page template only. If I use it as meta box for all pages, it won't make sense nor effect on other pages or page templates so I want to somehow make this particular template configurable – Dawid Adach Jul 9 '16 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.