How Can I keep password protected posts in the json requests but not on frontend queries?

I am attempting to exclude password protected posts from any frontend loop - inspired by this post

However, I have a custom angularjs admin theme that is activated when a user visits a certain post type and is logged in as an admin (ar-admin-page). This bypasses wp admin. It pulls posts to be manipulated by calling the Json wp api.

The problem: With the below in a mu-plugin, I can remove the password protected post from the frontend but it also removes posts from the json GET call . It seems the filter doesn't respect the query var check even though when I echo $query->query_vars['post_type'], I can see "ar-admin-page" as the post type.

function ar6_password_post_filter( $where = '', $query) {
    global $wpdb;
    // Make sure this only applies to loops / feeds on the frontend

    //  if it's not a single post, it's not an admin and it's not a particular post type request
    if ( !is_single()  !is_admin()  'ar-admin-page' != $query-query_vars['post_type'] ) {
        // exclude password protected
        $where .= " AND post_password = '' ";
     }
    return $where;
}
add_filter( 'posts_where', 'ar6_password_post_filter', 0, 2);

I also tried checking for the constant per this

config file

 define( 'JSON_REQUEST', true );

in my filter function

function ar6_password_post_filter( $where = '', $query) {
    global $wpdb;
    // Make sure this only applies to loops / feeds on the frontend

    //  if it's not a single post, it's not an admin and it's not a json request
    if ( !is_single()  !is_admin()  !JSON_REQUEST  ) {
        // exclude password protected
        $where .= " AND post_password = '' ";
     }
    return $where;
}
add_filter( 'posts_where', 'ar6_password_post_filter', 0, 2);

I'm really just looking to keep password protected posts in the json requests but not on the frontend.

What am I missing?

Topic posts-where rest-api Wordpress

Category Web


I sort of solved this by using this:

function ar6_password_post_filter( $where = '' ) {

   if (!is_single() && !current_user_can('edit_private_posts') && !is_admin()) {

        $where .= " AND post_password = ''";

    }

    return $where;

}

add_filter( 'posts_where', 'ar6_password_post_filter' );

This allows user roles of administrator and editor to still see the password protected posts on the front end of the site but hides them from anyone else.

However, I would still like to hide password protected posts from admins on the front end but but not in the json api - so if anyone has any suggestions, I'd appreciate it.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.