Create a custom query to only show subscribers posts they can access with Restrict Content Pro.
I recently was using Restrict Content Pro for the first time and the client asked for something that required a little bit of customization. They wanted a query to only display the posts a user had access to based on their Restrict Content Pro subscription level.
I did some Googling, but couldn’t find a quick solution so I rolled up my own using custom meta queries with the WP Query class.
Getting the User Subscription Level
The first thing I needed to do was to see if there was a way I could easily get the Access Level of the current user’s Subscription. This was easy enough to find by taking a look at the current user’s metadata. From there I was able to determine Restrict Content Pro saved the user’s access level with the meta key of
Getting the Post Access Level
I have the user’s access level, now I need to get the access level of each post to determine if the user’s level is high enough to view the post. Luckily Restrict Content Pro stores that data in the Post with a meta key of
rcp_access_level. Now I have the values I need to compare.
Writing the Custom WP Query
If you’re not familiar with custom WordPress queries check out the class reference page for WP Query on the Codex.
In this example I’m pulling in a custom post type called
resource. I’m then using a meta query to check if the post’s
rcp_access_level is less than or equal to the user’s
The problem with only using this is that posts that don’t have an access level set don’t get the
rcp_access_level metadata. So I’m also running a second meta query to return posts where the
rcp_access_level doesn’t exist by using the
NOT EXISTS comparison.
Here’s the full code:
$user_level = get_user_meta(get_current_user_id()); $args = array( 'post_type' => 'resource', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'rcp_access_level', 'compare' => '<=', 'value' => $user_level['rcp_subscription_level'], ), array( 'key' => 'rcp_access_level', 'compare' => 'NOT EXISTS', ), ), ); $resources = new WP_Query($args); if ( $resources->have_posts() : while ( $resources->have_posts() ) : $resources->the_post(); // Display post content here endwhile; endif; ?>
meta_query I’m using
'relation' => 'OR' to indicate I want WordPress to return the post if it matches the first OR second meta query. This way I get both the posts with an access level set through Restrict Content Pro and posts that are visible to everyone and don’t have an access level.
That’s it. If you’re more experienced with Restrict Content Pro and have a better method for handling this I’d love to hear it in the comments.