I have action which adds meta field with value on post publish. Problem is that when I update post meta field is reset to default value.
I already tried ‘new_to_publish’ instead of ‘publish_post’ but it doesn’t work.
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
update_post_meta($post_ID, 'votes_count', '0');
}
}
Still can’t make it work
add_action( 'transition_post_status', 'wpse120996_post_status_publish', 10, 3 );
function wpse120996_post_status_publish( $new_status, $old_status, $post_ID ) {
if ( $new_status == 'publish' && $old_status == 'pending' ) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
update_post_meta($post_ID, 'votes_count', '0');
}
}}
As I can understand it – every time status changes from pending to publish do whatever is inside if. But it doesn’t work.
In my site I have post rating system with meta field ‘votes_count’ where are stored votes. When I query votes_count from highest to lowest it doesn’t show posts with no votes, so I need to populate it with default value 0 to include them into query. Everything works fine but when i update votes are reset to 0… Posts are published by users with pending status which I check and publish.
Like @milo pointed out in the comment, checking if the post meta exists is the easiest way to achieve what you want – like this:
â On creation/publish not on updates
I’m keeping this, because it fits the matter of doing things on publish and not on update. But
auto-draft
âpublish
only works on first publishing a post and only if a post gets published directly. There might be the need to cover more cases, for exampledraft
âpublish
orpending
âpublish
.You could try:
instead of using
new_to_publish
.â Take a look at Post Status Transitions for additional information.
Or you could work with the generic hook
transition_post_status
like this:Another neat method doing things on publish or to be exact first creation and not on updates would be going like shown below. I opted for using the
save_post
hook, but this could be done with thepublish_post
hook too.This should work best:
Suprisingly it works. Maybe I’m not as stupid as I thought. Thank you both for help.