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

function save_my_metadata($ID = false, $post = false)
{
    if($post->post_type != 'your_post_type')
        return;
    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.

EDIT

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


If you want to handle multiple post types, I'd recommend a basic switch statement:

add_action('save_post', 'save_my_metadata');

function save_my_metadata($ID = false, $post = false)
{
    switch($post->post_type) 
    {
        case 'post_type_1':
            // Do stuff for post type 1
            update_post_meta($ID, 'my_metadata', $_POST['my_metadata']); // Example...
            break;
        case 'post_type_2':
            // Do stuff for post type 2
            break;
        default:
            return;
    }
}

The cases are basically the same as if($post->post_type) == 'post_type_1') {} But don't require multiple if-else blocks. The default block in the switch handles cases where the post type isn't in your custom set.


@John P Bloch and @EAMann have already given great answers so mine is in addition:

  1. Consider prefixing your meta_keys with an underscore. Doing so hides them from the list of custom fields displayed on a post edit screen, i.e.

    function save_my_metadata($post_id,$post=false) {
       if($post->post_type=='your_post_type')
          update_post_meta($post_id, '_my_metadata', $_POST['my_metadata']);
    }
    
    Obviously that means you'd need a custom metabox to be able to edit the fields too. Here's an edit screen for context:



  2. Another thing you could do is add your own hook to make saving specific post types easier, i.e. your hook could be "save_{$post_type}_post"; for a movie post type it would be save_movie_post. Here's what you'd have to add to your theme's functions.php file or in a plugin somewhere:

    add_action('save_post', 'save_custom_post_type_posts',10,2);
    function save_custom_post_type_posts($post_id,$post=false) {
       do_action("save_{$post->post_type}_post");
    }
    
    With that you could then rewrite your original code like so (including the underscore trick from #1 above):

    add_action('save_my_postype_post','save_my_postype_metadata',10,2);
    function save_my_postype_metadata($post_id,$post) {
        update_post_meta($post_id, '_my_metadata', $_POST['my_metadata']);
    }