I was searching for a way to automatically insert a custom field when publishing a custom post type. And I repeatedly found the same solution, from here:
http://pippinspages.com/tutorials/publish-action-hook-for-custom-post-types/
I’ve tried this and for some reason it’s just not working for me. I have a custom post type called sales_pages
Here’s my code:
// function to be executed when a custom post type is published
function run_when_post_published($post_ID)
{
// your function code here
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
add_post_meta($post_ID, 'field-name', 'custom value', true);
}
}
// replace {custom_post_type_name} with the name of your post type
add_action('new_to_publish_sales_pages', 'run_when_post_published');
add_action('draft_to_publish_sales_pages', 'run_when_post_published');
add_action('pending_to_publish_sales_pages', 'run_when_post_published');
Can you please give me a hint as to what is wrong with this?
I’ve confirmed this working with regular posts (with the post publish hooks of course). It’s just not doing the same for my custom post types.
Thanks in advance for any advice.
Cheers,
Bryan
There is no {$old_status}to{$new_status}_{$post_type} action hook. Examine the wp_transition_post_status function to see what types of hooks you can use there.
Instead, just use the generic transition_post_status hook. It gets the old and new statuses (so you can examine the status for changes) and the $post object itself, to let you examine the $post->post_type.
As Otto said, there are no ${old_status}to${new_status}_${post_type} action hook, but you can use the new_to_publish, draft_to_publish and pending_to_publish to add the post meta on your custom posts.
While I’m not an expert, here’s a couple of ideas:
Have you tried update_post_meta instead of add_post_meta? If the custom field already exists, add_post_meta probably won’t have any effect.
Are you sure that sales_pages is the “post slug”, which isn’t necessarily the same as the name of the custom post type? I remember struggling to try to figure out what the “post slug” is. Unfortunately, I forgot the answer.
You should hook
post_save
and check a couple of things:Something like: