skip to Main Content

I want to create a shortcode for my wp+woocommerce site, that will show the name of the current products category. I get the category id from my url with get request – this is a specialty. It will look something like:

function this_product_category_name() {
$cat_id = (int) str_replace('-product_cat', '', $_GET['really_curr_tax']);
// here must be a string to get the $cat_name from $cat_id;
echo $cat_name;
}

add_shortcode( 'this_product_category_name', 'this_product_category_name' );

What can be the solution?

2

Answers


  1. Since you’re on the product category page, then you could use get_queried_object, and then from that object you could get the name like so:

    $cat = get_queried_object();
    
    echo $cat->name;
    
    //or if you want to get its id 
    
    echo $cat->term_id;
    
    //if you want to see the object and what's in it then you could use print_r()
    
    print_r($cat);
    

    Let me know if that’s what you’re looking for.

    So your code would be something like this:

    function this_product_category_name() 
    {
    
      $cat = get_queried_object();
    
      echo $cat->name;
    
    }
    
    add_shortcode( 'this_product_category_name', 'this_product_category_name' );
    
    Login or Signup to reply.
  2. Use get_term_by().

    function this_product_category_name() {
        $cat_id = (int) str_replace('-product_cat', '', $_GET['really_curr_tax']);
        $product_cat = get_term_by( 'id', $cat_id, 'product_cat' );
        echo $product_cat->name;
    }
    add_shortcode( 'this_product_category_name', 'this_product_category_name' );
    

    USEFUL LINKS

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search