简体   繁体   中英

Wordpress: Output list with taxonomy term IDs in WP_Query loop

I would like to output in a WP_Query loop a list with the term IDs of a certain taxonomy ('genre') of the respective post. I managed to output the first ID (as you can see in the code example). How can I get a comma separated list of all term IDs of the taxonomy 'genre' for 'terms' in the 'tax_query' array?

function my_function( $query_args) {
    $terms = get_the_terms( $post->ID, 'genre');
    $termlist = $terms[0]->term_id;
    

$query_args = array(
    'post_type' => 'portfolio',
    'orderby' => 'date',
    'order' => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy' => 'genre',
            'field'    => 'term_id',
            'terms'    => array($termlist),
        ),
    ),
);

    return $query_args;

}

To return all ID's by your term, you need to use this:

$term_ids = []; // Save into this array all ID's

// Loop and collect all ID's
if($terms = get_terms('genre', [
    'hide_empty' => false,
])){
    foreach($terms as $term) {
        $term_ids[]=$term->term_id; // Save ID
    }
}

Now you can have array of term ID's by specific term and you can use join(',', $term_ids) function to made a comma separated list of IDs or anything you want.

But if you want to collect all term ID's by specific post, you need something like this:

$terms_ids = [];
if($terms = get_the_terms( $POST_ID_GOES_HERE, 'genre')){
    foreach($terms as $term) {
        $terms_ids[]=$term->term_id;
    }
}

But before you use get_the_terms you must be sure you have post ID provided or object ID defined.

In the your function you missing that part.

Here is update of the your function:

function my_function( $query_args ) {
    global $post; // return current post object or NULL
    
    if($post)
    {
        $terms_ids = array();
        if($terms = get_the_terms( $post->ID, 'genre')){
            foreach($terms as $term) {
                $terms_ids[]=$term->term_id;
            }
        }
        

        $query_args = array(
            'post_type' => 'portfolio',
            'orderby' => 'date',
            'order' => 'ASC',
            'tax_query' => array(
                array(
                    'taxonomy' => 'genre',
                    'field'    => 'term_id',
                    'terms'    => $terms_ids,
                ),
            ),
        );

        return $query_args;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM