Using WordPress ‘get_private_posts_cap_sql()’ PHP function

The get_private_posts_cap_sql() WordPress PHP function retrieves the private post SQL based on capability.

Usage

get_private_posts_cap_sql($post_type);

Parameters

  • $post_type (string|array) – Single post type or an array of post types. Currently only supports ‘post’ or ‘page’.

More information

See WordPress Developer Resources: get_private_posts_cap_sql()

Examples

Filter private posts for current user

This example filters the private posts for the current user with a custom query.

global $wpdb;
$user_id = get_current_user_id();
$post_type = 'post';

$cap_sql = get_private_posts_cap_sql($post_type);
$query = "SELECT * FROM $wpdb->posts WHERE post_type = %s AND {$cap_sql}";
$private_posts = $wpdb->get_results($wpdb->prepare($query, $post_type));

Custom function to retrieve private pages

Create a custom function to retrieve private pages for the current user.

function get_private_pages_for_current_user() {
    global $wpdb;
    $user_id = get_current_user_id();
    $post_type = 'page';

    $cap_sql = get_private_posts_cap_sql($post_type);
    $query = "SELECT * FROM $wpdb->posts WHERE post_type = %s AND {$cap_sql}";
    $private_pages = $wpdb->get_results($wpdb->prepare($query, $post_type));

    return $private_pages;
}

List private posts and pages in a dropdown

This example lists private posts and pages in a dropdown for the current user.

function private_posts_pages_dropdown() {
    $private_posts = get_private_pages_for_current_user();
    echo '<select>';
    foreach ($private_posts as $private_post) {
        echo '<option value="' . $private_post->ID . '">' . $private_post->post_title . '</option>';
    }
    echo '</select>';
}

Get private post count for current user

This example retrieves the private post count for the current user.

function get_private_post_count() {
    global $wpdb;
    $user_id = get_current_user_id();
    $post_type = 'post';

    $cap_sql = get_private_posts_cap_sql($post_type);
    $query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = %s AND {$cap_sql}";
    $private_post_count = $wpdb->get_var($wpdb->prepare($query, $post_type));

    return $private_post_count;
}

Get private posts for multiple post types

Retrieve private posts for multiple post types (e.g., ‘post’ and ‘page’) for the current user.

function get_private_posts_for_multiple_post_types() {
    global $wpdb;
    $user_id = get_current_user_id();
    $post_types = ['post', 'page'];

    $private_posts = [];
    foreach ($post_types as $post_type) {
        $cap_sql = get_private_posts_cap_sql($post_type);
        $query = "SELECT * FROM $wpdb->posts WHERE post_type = %s AND {$cap_sql}";
        $private_posts = array_merge($private_posts, $wpdb->get_results($wpdb->prepare($query, $post_type)));
    }

    return $private_posts;
}