1

I need to retrieve the name of all the categories that a given user has published posts for. If I can also get a URL for the archive of that cat for that user only, this would make me very happy.

How do I get a list of all categories that a given user has written blog posts for (and possibly the URL for that user's cat specific archive)?

What I've got so far:

From what I have learned, I have guessed:

  $args=array();
  $args['taxonomy']='categories';
  $args['hide_empty']=TRUE;
  $args['???']=$user_id;
  $list = get_terms( $args );

or maybe

  $cats = get_categories( 'hide_empty=0' . '???' );

One, both, or neither of these might be what I need. Can anyone help me get this across the finish line?

  • You're going to need SQL for this one. – Jacob Peattie Jun 13 '19 at 6:13
  • Dang. Should have expected that my luck would run out sooner or later. SQL it is then. – Matthew Brown aka Lord Matt Jun 13 '19 at 6:23
1

As, much as I know about WordPress we have to ways to achieve this.

First: You have to retrieve all posts written by an author an then you can fetch categories assigned to those posts. Store them in an array uniquely.

$args = array('author' => $author->ID, 'posts_per_page' => -1, 'fields' => 'ids');
$authorArticles = get_posts($args);
$postList = array();
foreach($authorArticles as $key => $article){
    if(!in_array($article, $postList)){
        $postList[$key] = $article;
    }
}
$termsList = array();
$siteURL = site_url('/category/');
foreach($postList as $article){
    $terms = get_the_terms($article, 'category');
    foreach($terms as $term){
        if(!isset($termsList[$term->term_id])){
            $termsList[$term->term_id] = ['term_id' => $term->term_id, 'term_url' => $siteURL.$term->slug];
        }           
    }
}
echo '<pre>', print_r($termsList), '</pre>';

Second: As, suggested by @Jacob you have to use SQL for retrieving list of categories.

Best Regards,

0

You don't need SQL (but it would be more direct, also harder to maintain…).

I understand you are looking for two things:

  • Get all categories of posts by one user (answered by first answer, IMHO)
  • Filter categories archive by author (answered here)

One of the joys of WordPress categories is that you can pass (almost) any of the variables in WP_Query in through the URL. So, to see a list of posts by user ID 1 for category ID 3, the URL would be https://example.com/?cat=3&author=1. Similarly, you can simulate this in code but you'll need to use a taxonomy query as you are querying posts, not categories (I know, that sounds weird but that's how it is).

See this for a really detailed list of ways to query WordPress

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.