Unable to get content from $post on first publish

I’m trying to get the title and content from the global $post variable when a user publishes a new post (to submit to an external web service, which in turn needs to pass back additional data to add to the post).

The hooks I tried using so far (‘transition_post_status’ and ‘publish_post’) all seem to run before the post is inserted into the database. This results in an empty string everytime my code tries to read data from $post, as (I assume?) this variable is fetched from the WordPress DB, and – because a new post is applicable – nothing has yet been stored in the DB to begin with.

Is there a hook that fires after a post’s status is transitioned to which I can hook a function? Alternatively, is it possible to somehow get the post title and content from the TinyMCE editor via PHP?

Would appreciate any help!

Example of what I’m currently sitting with:

add_action('transition_post_status','dostuff',10,2);

function dostuff( $new_status, $old_status ) {
    if ($new_status == 'publish' && $old_status != 'publish') {
        global $post;
        $content = $post-> post_title . "\n" . $post->post_content; //Title and content are empty :(
        //Do more stuff with $content
    }
}

2 Answers
2

The third parameter for transition_post_status is the post object. Use it.

add_action( 'transition_post_status', 'dostuff', 10, 3 );

function dostuff( $new_status, $old_status, $post ) {
}

When in doubt, do not use globals. They are not reliable, they make your code hard to test and to read.

Leave a Comment