Using WordPress ‘get_post_states()’ PHP function

The get_post_states() WordPress PHP function retrieves an array of post states from a given post.

Usage

$states = get_post_states($post);

Input: $post (WP_Post object)

Output: $states (Array)

Parameters

  • $post (WP_Post) – The post object to retrieve states for.

More information

See WordPress Developer Resources: get_post_states()

Examples

Display post states for a specific post

This example retrieves post states for a specific post and displays them.

$post_id = 42; // Replace with a specific post ID
$post = get_post($post_id);
$states = get_post_states($post);
echo implode(', ', $states);

Show post states in a list of posts

This example displays post states alongside post titles in a list of posts.

$posts = get_posts();
foreach ($posts as $post) {
    $states = get_post_states($post);
    echo "{$post->post_title} - " . implode(', ', $states) . "<br>";
}

Check if a post is password protected

This example checks if a post is password protected and displays a message accordingly.

$post_id = 42; // Replace with a specific post ID
$post = get_post($post_id);
$states = get_post_states($post);
if (in_array('password', $states)) {
    echo "This post is password protected.";
} else {
    echo "This post is not password protected.";
}

Check if a post is private

This example checks if a post is private and displays a message accordingly.

$post_id = 42; // Replace with a specific post ID
$post = get_post($post_id);
$states = get_post_states($post);
if (in_array('private', $states)) {
    echo "This post is private.";
} else {
    echo "This post is not private.";
}

Check if a post is sticky

This example checks if a post is sticky and displays a message accordingly.

$post_id = 42; // Replace with a specific post ID
$post = get_post($post_id);
$states = get_post_states($post);
if (in_array('sticky', $states)) {
    echo "This post is sticky.";
} else {
    echo "This post is not sticky.";
}