WordPress.org

Ready to get started?Download WordPress

Forums

Conditional add_meta_box using get_post_meta($post->ID,'_wp_page_template', true (3 posts)

  1. cvilela
    Member
    Posted 3 years ago #

    Good day,

    I'm "trying" to develop a plugin that works with a specific page template.

    A metabox will be added on the page edit screen only when the 'mbizpa.php' page template will be selected.

    The first thing I do is :

    if (get_post_meta($post->ID,'_wp_page_template', true) == 'mbizpa.php')
    {
      add_action( 'admin_init', 'myplugin_add_custom_box', 1 );
      add_action( 'save_post', 'myplugin_save_postdata' );
    }

    My problem is that the condition is never true.

    I can see 'mbizpa.php' on the database (and the mbizpa.php template is selected), but the condition is never true.

    I tried executing the same condition later in my plugin (at the spot where I do displays), and it works fine. The condition is true and I can display the 'mbizpa.php' value. I even displayed it in hex to make sure there is no blank space I cant see on the db. Nope, it's fine.

    When I change the condition to:

    if (get_post_meta($post->ID,'_wp_page_template', true) != 'mbizpa.php')

    Of course, the metabox is displayed on all page edit screens.

    - Would there be an easy way to display the value of _wp_page_template in a popup (alert box) for debug?

    - Why can't get the value of _wp_page_template right at the start of my plugin execution?

    Thanks for your help

    Christian

  2. cvilela
    Member
    Posted 3 years ago #

    I now understant hy this didn't work:

    if (get_post_meta($post->ID,'_wp_page_template', true) == 'mbizpa.php')
    {
      add_action( 'admin_init', 'myplugin_add_custom_box', 1 );
      add_action( 'save_post', 'myplugin_save_postdata' );
    }

    $post->ID is not set to any value.

    I think i've found my solution here:

    http://www.farinspace.com/page-specific-wordpress-meta-box/

    Instead of doing a get_post_meta to get the post ID, I can get it with the following code:

    $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;

    But, I still don't understand why $post->ID doesn't give me anything at the begining of my plugin, but later in the same plugin, I use it to display, and it works perfectly.

    Thanks again.

    Christian

  3. Stefan Boonstra
    Member
    Posted 2 years ago #

    You probably didn't define $post as a global variable in your plugin's function.

    function foo(){
    global $post;
    [Your code involving $post]
    }

Topic Closed

This topic has been closed to new replies.

About this Topic