Trong quá trình code giao diện với woocommerce bạn cần lấy danh mục gần nhất của sản một sản phẩm để tìm những sản phẩm liên quan cho sản phẩm hiện tại.Sau đây là đoạn code giúp trả về id của danh mục cấp thấp nhất của 1 sản phẩm
// get all product cats for the current post
$categories = get_the_terms( get_the_ID(), ‘product_cat’ );
// wrapper to hide any errors from top level categories or products without category
if ( $categories && ! is_wp_error( $category ) ) :
// loop through each cat
foreach($categories as $category) :
// get the children (if any) of the current cat
$children = get_categories( array (‘taxonomy’ => ‘product_cat’, ‘parent’ => $category->term_id ));
if ( count($children) == 0 ) {
// if no children, then echo the category name.
echo $category->name;
}
endforeach;
endif;
Với đoạn code này bạn có thể dễ dàng tìm sản phẩm liên quan hoặc bài viết liên quan