How to Show all the categories in which an Author has Posts – WordPress

This was a problem I came across when I was preparing an author page for a client. They wanted to show all the categories for which a certain user had written posts. For example, if there are 5 categories – A, B, C, D and E, and the user had created posts for categories B and D, then B and D should appear in the author profile page. I looked all through the Codex but was not able to find a function that would fulfil this requirement. So, decided to it the manual way.

Here is the code I have used –

[php]
$args = array(
‘author’ => $curauth->ID,
‘orderby’ => ‘postdate’,
‘order’ => ‘ASC’,
);
$a = array();
$user_posts = get_posts($args);
foreach($user_posts as $user_post) {
foreach(get_the_category($user_post) as $cat) {
$category_name = $cat->cat_name;
array_push($a, $category_name);
}
}
$a = array_unique($a);
[/php]

Here, $curauth is the variable storing the WP_User Object of the author whose categories you need to fetch. You can use get_userdata() to store the WP_User Object in $curauth.

Now, we need to fetch posts of the current user. That’s where the get_posts() function comes in. We pass the appropriate arguments to the function to fetch all the posts assigned to the user. The get_posts() function fetches the WP_Post object for every post that is assigned to the user. The WP_Post Object for every post is saved in the variable $user_posts().

Now, we are going to save category for each of these posts in the form of an array in the $a variable. For this, we are going to use the foreach loop. Without going into much detail, I am going to say that a nested foreach loop is required to fetch the category for each post and the category name is saved in the $category_name variable. The value in this variable is stored in $a variable using array_push.

Now, this $a variable is an array consisting of all the categories of all the posts assigned to the user. In order to avoid repeating values, we need to pass $a through array_unique which removes all the duplicate values (as posts having the same category will be saving their value in $a leading to multiple category values).

Now, you have an array of all the categories of posts from a user. Do whatever you want with it!

Let me know if you have any doubts regarding this method. Also, I am sure there’s a better method out there to do what I just did here. Feel free to share it in the comments.

 

Leave a comment

Your email address will not be published. Required fields are marked *