1

Which is the better way to get the current status of a post and why?

A:

$post_id = get_the_ID(); //999
$current_post_status = get_post_status($post_id);
echo $current_post_status; //publish

B:

$current_post_status = get_post_status();
echo $current_post_status; //publish

C:

$wp_post = get_post();
$current_post_status = $wp_post->post_status;
echo $current_post_status; //publish

D:

global $post;
$current_post_status = $post->post_status;
echo $current_post_status; //publish
  • That depends on where you are trying to fetch the status. Suppose, get_the_ID() will return a wrong ID, if you are not using it within 'the loop`. Please edit your question and add the perspective where you want to fetch the post status. – Mayeenul Islam Mar 9 '19 at 4:00
2

None of them.

A, C and D all indicate that you're inside a loop, and want the status for the current post. But if that's the case then the first line on all of them is redundant. This is all you'd need if you want the status of the 'current post':

$current_post_status = get_post_status();

get_post_status() calls get_post() internally, which gets the current post for you. So providing it the ID of the current post, or the current post's object, is unnecessary.

If you want the status of a post that is not the current post, then use the get_post_status() function and pass a full post object, if you have it:

$current_post_status = get_post_status( $post );

Otherwise use the function and pass an ID:

$current_post_status = get_post_status( 12 );

You should prefer passing the whole post object, rather than just the post ID. This is because otherwise the get_post_status() function will need to do the work internally to turn the ID into a post object itself, which is a waste of time if you've already got the full object.

The advantage of get_post_status() over $post->post_status is that the function has additional logic to handle the status of attachments, which might be relevant, and it also passes the result through the get_post_status filter, which could be important if you're using a plugin that interacts with the post status in some way.

If a function is available to get a post's property, then that will usually be preferable to accessing the property directly, if only because it will apply the correct filters to the result.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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