Skip to content

Instantly share code, notes, and snippets.

@mcurren
Last active December 15, 2017 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcurren/850573eaa6259d6c9012445835eedcc8 to your computer and use it in GitHub Desktop.
Save mcurren/850573eaa6259d6c9012445835eedcc8 to your computer and use it in GitHub Desktop.
Wordpress post meta query for Members plugin roles

Wordpress Members plugin post Meta Query

A meta query to be used with the Members plugin by Justin Tadlock. This meta query and will not have any effect without the plugin installed and active.

Description

This Meta Query has two arguments and accepts either one. They are both based on post meta assigned using the Members plugin Content Permissions meta box on the post edit screen.

Members plugin Content Permissions meta box

Argument 1

This meta query argument will exclude any posts from your custom WP_Query with roles assigned in the Content Permissions meta box that do not match the current user's role.

Argument 2

Since the first argument also hid posts that did not have any role assigned in the Content Permissions meta box, I added this second post to be inclusive of those posts by default.

Alternative usage

You could easily use this code with a different membership or content restriction plugin by substituting the _members_access_role key with the post meta key your plugin uses.

<?php
// set up current user role meta query
global $current_user;
$current_user_roles = array_keys($current_user->caps);
// define role-based meta query
$user_role_meta_query = array(
'relation' => 'OR',
// argument #1 - any user roles attached to post match any $current_user_roles
array(
'key' => '_members_access_role',
'value' => $current_user_roles,
'compare' => 'IN',
),
// argument #2 - no user roles attached to post
array(
'key' => '_members_access_role',
'compare' => 'NOT EXISTS',
),
);
// use it in a custom query
$your_custom_query_args = array(
'post_type' => 'post',
'meta_query' => $user_role_meta_query,
);
$your_custom_query = new WP_Query($your_custom_query_args);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment