I have a website with multiple authors and I want to those authors could only see their own added posts and posts that have some specific custom field.
So I used this code for restriction at the first step and worked, but this code restrict authors to see only their own added posts:
function pposts_for_current_author($query) {
global $pagenow, $parent_file, $post_type;
$user = wp_get_current_user();
if('movie' == $post_type || 'edit.php' != $pagenow || !$query->is_admin ) {
return $query;
}
if(!current_user_can( 'edit_user', $user_id )) {
global $user_ID;
$query->set('author', $user_ID );
}
return $query;
}
add_filter('pre_get_posts', 'pposts_for_current_author');
Then I just combined this code with get_post_meta
function:
function pposts_for_current_author($query) {
global $pagenow, $parent_file, $post_type;
$user = wp_get_current_user();
$moviePublic = get_post_meta($post->ID, 'movie_multi_author', true);
if('movie' == $post_type || 'edit.php' != $pagenow || !$query->is_admin ) {
return $query;
}
if(!current_user_can( 'edit_user', $user_id ) && $moviePublic == 1) {
global $user_ID;
$query->set('author', $user_ID );
}
return $query;
}
add_filter('pre_get_posts', 'pposts_for_current_author');
I don’t exactly what should I doing with this code. Anyone could make it right please? Thanks.
2
Answers
It looks like you’re trying to restrict authors on your WordPress website to see only their own posts and posts with a specific custom field. The code you provided seems to be on the right track, but there are a few issues and improvements needed. Here’s a revised version of your code:
Here’s what’s changed or added:
$parent_file
and$user
.get_current_user_id()
to get the current user’s ID.With these changes, this code should work to restrict authors to see their own posts and posts with the specified custom field. Just make sure you have the custom field ‘movie_multi_author’ set correctly for the posts you want to be visible to multiple authors.
I understand your concern. If you want the query to work with both the author restriction and the custom meta_key, you can modify the code like this:
This code uses the
'relation' => 'OR'
parameter within themeta_query
array to combine the author query and the custom meta_key query. This way, it should retrieve posts authored by the current user and posts with the specified custom field ‘movie_multi_author’ set to 1. You can also add additional meta queries as needed within themeta_query
array if you have other conditions to check.