0

My plugin does stuff whenever a post is published and comments are enabled for that post. It works fine when publishing a post as normal, but if a scheduled post is published, it doesn't.

Here's what my code looks like:

function do_stuff( $new_status, $old_status, $post ) {
    global $post;

    if ( !comments_open( $post->ID ) ) {
        return;
    }

    /* do stuff */
}
add_action( 'transition_post_status', 'do_stuff', 10, 3 );

After some debugging, I was surprised to find the problem was comments_open() returning FALSE, every single time a scheduled post was published, regardless of the "Allow Comments" setting.

Why is this happening?

2
  • Can you check what $post->comment_status returns in these cases?
    – Emil
    Nov 25, 2016 at 8:53
  • No, $post->comment_status is empty when a scheduled post is published. I'm guessing this is why comments_open() doesn't work, because the $post object hasn't been fully initialized yet...
    – DeltaHF
    Nov 26, 2016 at 1:36

1 Answer 1

2

The problem was caused by referencing the global $post object. The global $post has not yet been initialized with the new post's details, so checking to see whether or not its comments are open will always return false at the transition_post_status hook.

The $post variable passed to my do_stuff() function does contain all the correct information about my new post, so I work with it instead. I eventually ended up with something like the following, which functions correctly with both regular and scheduled posts:

function do_stuff( $new_status, $old_status, $post ) {
   if ( $post->comment_status == 'closed' ) {
     return;
   }

   /* do stuff */
}
add_action( 'transition_post_status', 'do_stuff', 10, 3 );
2
  • Ah, good catch, that makes perfect sense.
    – Emil
    Nov 28, 2016 at 8:34
  • 1
    Thank you...your post helped me with a different but similar situation. Comments were disabled...because a shortcode in the page didn't reset the global post. I added wp_reset_postdata(); to the end of the shortcode function and that did the trick. Hope this helps others. May 6 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.