Home › Forums › General Issues › CPT query with taxonomy field
Hi.
My challange:
With the help of the taxonomy field (“inspo_kategorie”/return = post object) I want to create a query that gives me all the posts of the selected taxonomy(s) of my CPT “inspiration”.
If it is relevant: The taxonomy field is located in an custom (ACF) gutenberg block. The output of “normal” (text)fields is working.
Here is my code:
<?php
$category = get_field('inspo_kategorie');
$inspo = new WP_Query( array(
'post_type' => 'inspiration',
'posts_per_page' => 3,
'post_status' => 'publish',
'tax_query' => array(
array(
'field' => 'slug',
'terms' => $category
)
)
));
?>
<?php if ( $inspo->have_posts() ) : ?>
<!-- pagination here -->
<?php while ( $inspo->have_posts() ) : $inspo->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
I can’t find the mistake…
The output is: “Sorry, no posts matched your criteria.”
This is the var_dump of “$category” (outputs the selected taxonomys correctly)
array(2) {
[0]=>
object(WP_Term)#9654 (10) {
["term_id"]=>
int(12)
["name"]=>
string(14) "Brillen-Studio"
["slug"]=>
string(14) "brillen-studio"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(12)
["taxonomy"]=>
string(8) "bereiche"
["description"]=>
string(34) "Inspiration aus dem Brillen-Studio"
["parent"]=>
int(0)
["count"]=>
int(3)
["filter"]=>
string(3) "raw"
}
[1]=>
object(WP_Term)#9646 (10) {
["term_id"]=>
int(13)
["name"]=>
string(20) "Contactlinsen-Studio"
["slug"]=>
string(20) "contactlinsen-studio"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(13)
["taxonomy"]=>
string(8) "bereiche"
["description"]=>
string(0) ""
["parent"]=>
int(0)
["count"]=>
int(1)
["filter"]=>
string(3) "raw"
}
}
As far as I understand it, according to https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters the terms must be an array of terms, not a category object, as your $category
is returning. So, you need to loop over the $category
object to retrieve the single terms and store them in an array first.
The topic ‘CPT query with taxonomy field’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.