I use save_post
hook, and I have to know inside this hook function, whether it is a publishing ( draft to publish
) or is it an updating, like publish to publish
or draft to draft
.
Is there a way to check it?
I can not use draft_to_publish
hook for this, and I’ll explain why:
The users ask questions on the site, and questions are saved as draft
posts. A site admin write an answer and then publish the post. A post has meta box
“status” that can have next values: “not answered”, “treatment”, “answered”. A site admin may change this value as he wants, but when he publish the post (draft to publish, or draft to private), this meta value must be changed automatically to “answered” (although that the input area
on admin area has another value). So I have a function that fired on save_post
hook, that save all values according to input area
values. And also I tried to use draft_to_publish
hook to assign “answered” to the meta value. The problem is that save_post
always fired after draft_to_publish
, so that the value (“answered” that assigned on draft_to_publish
) is overridden by the value of input area
.
2 Answers
There are hooks specifically for this, actually. The codex has a pretty good overview.
Essentially every time WordPress saves a post (which it does through wp_insert_post
) or alters the status of the post, it calls wp_transition_post_status
which looks like this:
<?php
// in wp-includes/post.php
function wp_transition_post_status($new_status, $old_status, $post) {
do_action('transition_post_status', $new_status, $old_status, $post);
do_action("{$old_status}_to_{$new_status}", $post);
do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
}
So, if you want to check for a post moving from publish to publish you could do this…
<?php
add_action('transition_post_status', 'wpse83835_transition', 10, 3);
function wpse83835_transition($new, $old, $post)
{
if ('publish' == $new && 'publish' == $old) {
// do stuff
}
}
Or this…
<?php
add_action('publish_to_publish', 'wpse83835_transition_again');
function wpse83835_transition_again($post)
{
// do stuff.
}