Reputation: 76601
Let's suppose the user visits the page of
http://mywpsite/wp-admin/edit.php?author=john-doe
Let's suppose there is an author with the name of 'John Doe'
and the given author has three posts. Yet, when I visit the page, I see an empty grid, as if there were no posts created by this author.
I would like to search for posts created by the given user. Based on my research, I can see that people are claiming that something like this should work:
function posts_for_current_author($query) {
if($query->is_admin) {
global $user_ID;
$query->set('author', $user_ID);
}
return $query;
}
add_filter('pre_get_posts', 'posts_for_current_author');
However, here the author's ID is expected as input, yet, I do not know how to get the author's id by the slug of 'john-doe'
.
How can I get the ID of the author by slug and search for posts based on that ID?
EDIT:
This is one failed try, based on NATH's comment:
function wpshock_search_filter( $query ) {
if ((is_admin()) && (isset($_GET["author"])) && (preg_match('/[^a-zA-Z_0-9]/i', $_GET["author"]))) {
$query->set("author_name", $_GET["author"]);
}
return $query;
}
add_filter('pre_get_posts','wpshock_search_filter');
The query still returns no elements. I have var_dump
ed $query
and seen that $query->query["author"]
has the textual problem, which is a potential problem. Also, $query->tax_query
contains data related to author. I am sorry if this question is worthy of down-votes, I thought others might be confused by Wordpress's database handling as well and thus this question might be useful. Maybe I was wrong.
Upvotes: 0
Views: 2323
Reputation: 774
I'm wotking on wp front-end and reach similar feauture you are requested
The code you provide are woking current on wp-admin page but any one uses that code prevent his own SuperAdmin account form reviewing other editors posts .
just add !is_super_admin()
to your first contition like this :-
if($query->is_admin && !is_super_admin() )
BTW the author's ID are already provided with global $user_ID;
and when you add this $query->set('author',$user_ID);
the main query will filter posts result accurding to author ID , see WP_Query();
Upvotes: 1
Reputation: 27102
WordPress provides an author_name
query variable to you. You can use the following by default:
http://mywpsite/wp-admin/edit.php?author_name=john-doe
Read more about public query variables in the Codex.
Upvotes: 1
Reputation: 463
See this-
https://wordpress.stackexchange.com/questions/89990/how-we-can-get-the-author-id-by-its-name
And, a better way to get posts by an author would be-
get_posts('author'=>AUTHOR_ID);
Upvotes: 0
Reputation: 761
This should work for you :
get_user_by('slug','john-doe');
EDIT : From this you can get author object and you can carry forward with your code.
Upvotes: 2