TransWikia.com

get_terms (or tax_query) for term of current post?

WordPress Development Asked by FNTC on October 18, 2020

I’ve seen many solutions but none seem to work for me… I’ve got a grid off the loop/content on single.php that renders the whole grid as is, so I use the function as below which works fine, but only if I specify the exact taxonomy term (client-1).

function my_query_args($query_args, $grid_name) {
if ($grid_name == 'client-grid') {
    $query_args['tax_query'] = array(
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => 'client-1',
        ),
    );
}
return $query_args;
}
add_filter('tg_wp_query_args', 'my_query_args');

But I want the term of the current post instead so I thought that below would work, but it renders all posts in the grid no matter what I do.

function my_query_args($terms_list, $grid_name) {
if ($grid_name == 'client-grid') {

    $terms_list = get_terms
        (array(
            'taxonomy' => 'category',
            'parent' => 0,
        )
    );  
}
return $terms_list;

}
add_filter('tg_wp_query_args', 'my_query_args'); 

Thankful for any input.

EDIT

Thinking of something like this (which obvs doesn’t works), but anyone that can point in the right direction?

$term_id = get_queried_object_id();

function my_query_args($query_args, $grid_name) {
if ($grid_name == 'JTS-SINGLE') {

    $query_args['tax_query'] = array(
        array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => $term_id
        ),
    );
}
return $query_args;

}
add_filter('tg_wp_query_args', 'my_query_args', 10, 2);

2 Answers

SOLVED

This was what I was looking for and it works like a charm.

function my_query_args($query_args, $grid_name) {

$term_list = get_the_terms( get_the_ID(), 'category' )[0]->slug;

if ($grid_name == 'JTS-SINGLE') {
    $query_args['tax_query'] = array(
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => array( $term_list ),
        ),
    );
}
return $query_args;

}
add_filter('tg_wp_query_args', 'my_query_args', 10, 2);

Answered by FNTC on October 18, 2020

Have a look at wp_get_post_terms which allows you to specify a posiID, which is what I think you are getting at

Answered by essexboyracer on October 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP