Trouble with wordpress WP_Query by tags

I’m trying to query custom post type of products and all the tags inside the $terms variable. I want this to work whether there is a single tag or multiple tags. The tags are not unique to the business types but general post tags

here is what I have so. I’m pretty sure the issue is in the tax_query section


      $terms = get_field('tags_for_products');
      if ($terms) {
        if (!is_array($terms)) {
          $terms = array($terms);
        }
      }

      $args = array(
        'post_type' => 'product',
        'posts_per_page'   => -1,
        'orderby' => 'rand',
        'tax_query' => array(
          array(
            'taxonomy' => 'tag',
            'field' => 'slug',
            'terms' => $terms,
          ),
        ),
      );

      $products = new WP_Query($args);

this is the current array inside the $terms variable.

Array ( [0] => WP_Term Object ( [term_id] => 98 [name] => Hats [slug] => hats [term_group] => 0 [term_taxonomy_id] => 98 [taxonomy] => post_tag [description] => [parent] => 0 [count] => 0 [filter] => raw ) [1] => WP_Term Object ( [term_id] => 96 [name] => Hoodie [slug] => hoodie [term_group] => 0 [term_taxonomy_id] => 96 [taxonomy] => post_tag [description] => [parent] => 0 [count] => 0 [filter] => raw ) )

I think the problem here is that your terms should not be an array of WP_Term objects, they should be an array of strings or integers (like if you are using IDs). Something like…

array(
   'taxonomy' => 'tag',
   'field' => 'slug',
   'terms' => ['hoodie','hats','shirts']
);

Here we are saying products where their slugs are hoodie, hats or shirts. For more information check out the examples on https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters

:slight_smile:

Your problem is that the $terms var contains WP_Term objects while you are setting up the taxonomy query to expect an array of term slugs. If you have an array of WP_Term objects and you wish to grab value of a certain field from each object then you can use wp_list_pluck() to do that.

Also, the taxonomy slug is post_tag & not tag - so you have that incorrect in your taxonomy query as well.

This code here should work for you:

$terms = get_field( 'tags_for_products' );
$terms = ( ! empty( $terms ) ) ? wp_list_pluck( (array) $terms, 'slug' ) : [];

$args = array(
	'post_type'      => 'product',
	'posts_per_page' => -1,
	'orderby'        => 'rand',
	'tax_query'      => array(
		array(
			'taxonomy' => 'post_tag',
			'field'    => 'slug',
			'terms'    => $terms,
		),
	),
);

$products = new WP_Query( $args );

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.