I've created a custom product details page and am trying to get the category of that product but it's not working.

I have created a form where people will fill out questions like:

What brand do you like?

Click next...

What model do you like?

Click next and so on. It will grab products based on their filled information.

Here is my code

if ( isset( $_REQUEST['product_tag'] ) ) {
    $tags = $_REQUEST['product_tag'];

$args = array( 
    'post_type'      => 'product', 
    'posts_per_page' => 1, 
    'product_tag'    => $tags 
$loop           = new WP_Query( $args );
$product_count  = $loop->post_count;

if ( $product_count > 0 ) :
    while ( $loop->have_posts() ) :
        global $product;        
        global $post;
        $thePostID = $post->post_title;
        //echo '<img src="'.$woocommerce->plugin_url().'/assets/images/placeholder.png" alt="" width="'.$woocommerce->get_image_size('shop_catalog_image_width').'px" height="'.$woocommerce->get_image_size('shop_catalog_image_height').'px" />';
        $terms = wp_get_object_terms($post->ID, 'product_cat'); 
        echo $terms->name;

        // ...
  • 1
    Welcome to WPSE! Unfortunately, 3rd Party Plugins ( such as WooCommerce ) are considered to be off-topic here and would be better suited on the WordPress forums or handled by their support. That being said - I think you may need to use a Tax Query instead for $tags. – Howdy_McGee Aug 3 '16 at 20:07

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;

      // ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.