0

I've got a custom taxonomy "sector" associated to posts; posts are assigned to the default categories as well. What I'd like to achieve is to show in a custom sidebar a list of "categories" link/name, the post of which are assigned to the selected "sector".

Eg.: say that my data are organized like this (hope this make sense), with three posts associated to a various categories AND to a particular sector:

Post 1

  • category: category_1
  • sector: sector_1

Post 2

  • category: category_2
  • sector: sector_1

Post 3

  • category: category_3
  • sector: sector_1

Now, when I'm in the "sector_1" archive page, in the sidebar I'd like to show the following list:

  • category_1
  • category_2
  • category_3

Is this possible? Maybe using tax_query or other methods?

2
  • @vancoder actually I wrote "woocommerce" but the question could be applied to Wordress as well. Can I re-edit/re-name the thread? Commented Oct 26, 2021 at 17:07
  • Feel free to make it more generic.
    – vancoder
    Commented Oct 26, 2021 at 17:49

1 Answer 1

0

Here's what I come up with, looks like it's working. But maybe (surely) there's a more efficient way to do the same:

// current queried
$term = 'sector';
$current_sector_id = get_queried_object_id();

// Prepare wp_query to get all posts assigned to the current "sector" 
$sector_posts_query = new WP_Query();
$sector_posts_query->query(
    array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => $term,
                'field' => 'term_id',
                'terms' => $current_sector_id
            ),
        )
    )
);

// loop the posts
if ($sector_posts_query->have_posts()) {
    $terms_array = array();
    while ($sector_posts_query->have_posts()) : $sector_posts_query->the_post();
        // get the product_cat of each post and store it as arrays in the $terms_array
        $current_category_terms = get_the_terms(get_the_ID(), 'my_category');
        $terms_array[] = wp_list_pluck($current_category_terms, 'term_id');
    endwhile;
    wp_reset_postdata();
}
// merge the inner arrays and remove doubles
$result = call_user_func_array("array_merge", $terms_array);
$result = array_unique($result, SORT_REGULAR);

echo '<ul>';
foreach ($result as $id) {
    $my_category = get_term_by('id', $id, 'my_category');
    $my_category_url = get_term_link($id, 'my_category');
    echo '<li><a href="' . $my_category_url . '">' . $my_category->name . '</a></li>';
}
echo '</ul>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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