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.
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:
The cases are basically the same as
if($post->post_type) == 'post_type_1') {}
But don’t require multiple if-else blocks. Thedefault
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:
Obviously that means you’d need a custom metabox to be able to edit the fields too.
Here’s an edit screen for context:
save_{$post_type}_post
“; for amovie
post type it would besave_movie_post
. Here’s what you’d have to add to your theme’sfunctions.php
file or in a plugin somewhere:With that you could then rewrite your original code like so (including the underscore trick from #1 above):
Personally, I prefer to follow the below pattern for adding custom meta handlers to post types. With the below, you can add the meta support to a post type by just adding the supports key (‘subtitle’ in the example below) to the supports array for the post type by calling add_post_type_support(‘my_post_type’, ‘subtitle’);
Hopefully something like this will soon be added into core.
Prior updating check whether or not the current post is of your post-type. That would ensure you don’t save it for all posts.
You should check for the input as well (that’s missing in your example) and next to that, keep in mind that you might only add the action when that post-type is active. If that’s the case, you do not need to check for that post-type later on.
Getting a posts type:
get_post_type()
or$post->post_type;
I cant get this to work – not sure what Im doing wrong – but Im trying to use post_updated hook instead of the save_post – as I want these values to be inserted after the post has been updated so I can retrieve values from the other custom fields.