get_post_meta giving errors while creating a metabox

i was following atutorial on how to make a custom metabox to wordpress post but
its giving errors

here is my full code

//Add Metabox
function diwp_custom_metabox(){
    //add_meta_box(metabox_id,metabox name,callback function,metabox location(page,post,custom post etc),context-(normal,side,advanced),piority())
    add_meta_box('diwp-metabox','My Custom Metabox','diwp_post_metabox_callback','post','normal');
}

//add action
add_action('add_meta_boxes','diwp_custom_metabox');
//metabox callback function

function diwp_post_metabox_callback(){
    // echo 'hi i am diwp metabox';
    ?>
    <div class="row">
      <div class="label">Post Reading Time</div>
      <div class="fields">
        <input type="text" name="_diwp_reading_time" value="<?php get_post_meta($post->ID,'post_reading_time',true); ?>">
      </div>
    </div>
    <?php
}

function diwp_save_custom_metabox(){
    // update_post_meta($post_id,$meta_key,$meta_value,$prev_value);
    global $post;
    if(isset($_POST['_diwp_reading_time'])){
        update_post_meta($post->ID,'post_reading_time',$_POST['_diwp_reading_time']);
    }
}

add_action('save_post','diwp_save_custom_metabox');

error screen shot
get_post_meta giving errors while creating a metabox

any help will be appreciated ,thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The error there clearly says that there’s an undefined variable (post) in your metabox callback function.

So you need to define $post in your function head:

// The $post variable is passed by WordPress.
function diwp_post_metabox_callback( $post )

And you should also do the same to diwp_save_custom_metabox() function (which is hooked to save_post):

// Here, $post is the second parameter.
function diwp_save_custom_metabox( $post_ID, $post ) {
    // ...
}

// Don't forget to set the 4th parameter to 2:
add_action( 'save_post', 'diwp_save_custom_metabox', 10, 2 );

Or alternatively, use get_post() and not the global call:

// Here, $post is the second parameter.
function diwp_save_custom_metabox( $post_ID ) {
    $post = get_post( $post_ID ); // like this
//  global $post;                 // not this

    // ...
}

add_action( 'save_post', 'diwp_save_custom_metabox' );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x