9

I have a wp template that I would like to assign to some pages. The template would ie. display all WooCommerce products that have the same master category name as the pages name itself.

By far I have tried using this code, but with no good output:

$idObj = get_category_by_slug($pagename);
$id = $idObj->term_id;
echo ": ". $id;

Unfortunately, the echo does not display anything.
Echoing $pagename works, and returns me the slug of the page.

Any good way I could make this work?

7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
aln447
  • 981
  • 2
  • 15
  • 44

2 Answers2

32

With a custom taxonomy is recommended to use get_term_by() instead :

$category = get_term_by( 'slug', $pagename, 'product_cat' );
$cat_id = $category->term_id

Reference: Get category ID from term slug…


To get a product category ID from term name, use:

$category = get_term_by( 'name', $pagename, 'product_cat' );
$cat_id = $category->term_id
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
0

The code seems to be correct, try a var_dump to see what you are getting from get_category_by_slug($pagename)

$idObj = get_category_by_slug($pagename);
var_dump($idObj);
Igor S Om
  • 735
  • 3
  • 12
  • 1
    Just for reference: This is for Wordpress "categories". WooCommerce categories use "product_cat" so you have to use get_term_by() – Bossman Jan 20 '21 at 11:49