Introducing additional functions to check if a post is publicly viewable in WordPress 5.7

WordPress 5.7 introduces two additional functions to check if a post is publicly viewable.

Previously, the is_post_type_viewable() function was already available to determine if a post type is visible to anonymous users via the publicly_queryable setting when registering the post type. However, it wasn’t sufficient to determine if a specific post is viewable as this function only checks for general post type settings.

That’s why WordPress 5.7 introduces is_post_status_viewable() function, which allows developers to determine whether a post status is publicly viewable or not. Internal and protected statuses are never considered viewable. For built in posts statuses the public attribute is checked, for custom statuses the publicly_queryable attribute is checked.

This function accepts one parameter:

  • $post_status: The post status name or object. This parameter is required.

Usage example:

<?php
global $post;
$current_post_status = get_post_status( $post );
if ( is_post_status_viewable( $current_post_status ) ) {
	echo 'This post uses a public post status';
} else {
	echo 'This post uses a non public post status';
}

Please note that password protected posts are considered publicly viewable, while private posts are not.

WordPress 5.7 also introduces is_post_publicly_viewable() for determining if an individual post can be viewed by logged out users. A post is considered viewable if both is_post_status_viewable() and is_post_type_viewable() return true for the post’s attributes.

This function accepts one parameter:

  • $post: A post ID or a post object. This parameter is optional. By default it passes the global $post object.

Usage example:

<?php
if ( is_post_publicly_viewable() ) {
	echo 'This post is publicly viewable';
} else {
	echo 'This post is not publicly viewable';
}

Additionally, the is_post_type_viewable() function was modified to return false if an unregistered post type is passed to the function to avoid attempting to access properties on a non-object.


For reference, see ticketticket Created for both bug reports and feature development on the bug tracker. #49380

Props @peterwilsoncc for proofreading

#5-7, #dev-notes