Using WordPress ‘is_post_publicly_viewable()’ PHP function

The is_post_publicly_viewable() WordPress PHP function determines whether a post is publicly viewable.

Usage

$is_viewable = is_post_publicly_viewable($post);

Input: $post (Post ID or post object, optional)

Output: true if the post is viewable, false otherwise

Parameters

  • $post (int|WP_Post|null, optional): Post ID or post object. Defaults to global $post. Default value: null

More information

See WordPress Developer Resources: is_post_publicly_viewable()

Examples

Check if the current post is publicly viewable

$is_viewable = is_post_publicly_viewable(); // Defaults to the current post
if ($is_viewable) {
    echo "This post is publicly viewable.";
} else {
    echo "This post is not publicly viewable.";
}

Check if a specific post is publicly viewable by ID

$post_id = 42;
$is_viewable = is_post_publicly_viewable($post_id);
if ($is_viewable) {
    echo "Post ID $post_id is publicly viewable.";
} else {
    echo "Post ID $post_id is not publicly viewable.";
}

Check if a specific post is publicly viewable using a WP_Post object

$post = get_post(42);
$is_viewable = is_post_publicly_viewable($post);
if ($is_viewable) {
    echo "Post ID {$post->ID} is publicly viewable.";
} else {
    echo "Post ID {$post->ID} is not publicly viewable.";
}

Display a list of publicly viewable posts

$posts = get_posts();
foreach ($posts as $post) {
    if (is_post_publicly_viewable($post)) {
        echo "<a href='" . get_permalink($post) . "'>" . get_the_title($post) . "</a><br>";
    }
}

Display the viewable status of all posts in the loop

while (have_posts()) {
    the_post();
    if (is_post_publicly_viewable()) {
        echo "Post ID " . get_the_ID() . " is publicly viewable.<br>";
    } else {
        echo "Post ID " . get_the_ID() . " is not publicly viewable.<br>";
    }
}