You have a few things that are wrong.
- remove global variable as we are already working in a custom loop no need for global $post or other globals.
- Get all posts with that selected tag in the
$args
(assuming this is what you want). - If you know the type of request, I’d use
$_GET
or$_POST
accordingly instead of$_REQUEST
. $terms
is an object, so you need to iterate over it to get the info you want- Here I hooked this example to
init
but you might want to hook later depending on your code.
.
add_action('init', 'wpse_233955' );
function wpse_233955 (){
if ( isset( $_REQUEST['prod_tag'] ) ) {
$tags = $_REQUEST['prod_tag'];
}
$args = array(
'post_type' => 'product',
'posts_per_page' => -1, // Get all post with the tag not just 1
'product_tag' => $tags
);
$query = new WP_Query( $args ); // $query is you custom loop
$product_count = $query->post_count;
if ( $product_count > 0 ) :
while ( $query->have_posts() ) :
$query->the_post(); // This will set the $query object to the current post item
$thePostID = get_the_ID();
$terms = wp_get_object_terms( $thePostID, 'product_cat');
foreach( $terms as $term ){
echo $term->name;
}
// ...
endwhile;
endif;
}