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 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 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,

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.