How do I save metadata for a specific custom post type only?

I’m trying to set up a custom post type following this tutorial. However, I’m a bit confused as how/where to implement update_post_meta(). The tutorial suggests this pattern:

add_action('save_post', 'save_my_metadata');

function save_my_metadata()
    global $post;
    update_post_meta($post->ID, 'my_metadata', $_POST['my_metadata']);

Which does work, but has the unfortunate effect of adding that metadata to each and every post, whether it belongs to this custom type or not.

I’ve put the above in functions.php and am guessing that might be part of the problem. I’m guessing I need to restrict the ‘save_post’ action to only trigger for posts of my custom type.


function save_my_metadata($ID = false, $post = false)
    if($post->post_type != 'your_post_type')
    update_post_meta($ID, 'my_metadata', $_POST['my_metadata']);

That should work. Just replace ‘your_post_type’ with the name of the post type. Also, little known fact: the ‘save_post’ hook passes the post’s ID as an argument.


I updated the function to reflect Jan’s comment. Thanks Jan!

Leave a Comment