Issue
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;
}
Solution
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,
])){
$term_ids[]=wp_list_pluck($terms, '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')){
$term_ids[]=wp_list_pluck($terms, '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')){
$term_ids[]=wp_list_pluck($terms, '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;
}
}
Answered By - Ivijan Stefan Stipić
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.