问题描述
-electronic
-- laptop
-- mobile
然后我想为electronic
下的所有产品创建一个逻辑,我使用is_product_category( ‘electronic’ )
,但它不适用于电子产品,它仅在URL为mywebsite.com/product-category/electronic
时有效,当我使用 mywebsite.com/product-category/electronic/mobile/
它不起作用。我应该使用以下代码还是有其他选择:
is_product_category( ‘laptop’ )
is_product_category( ‘mobile’ )
解决方法
您可以创建一个自定义条件函数,该函数还可以处理产品类别档案中的任何子产品类别,例如 (处理术语名称、术语 slug 或术语 ID):
/**
* Determines whether the query is for an existing product category archive page or for an ancestors product category archive page.
*
* @param int|string term ID,term slug or term name to check.
* @return bool
*/
function is_maybe_child_product_category( $category ){
if( is_product_category( $category ) ) {
return true;
}
$object = get_queried_object();
if( ! is_a( $object,'WP_Term') ) {
return false;
}
$taxonomy = $object->taxonomy;
$children = get_term_children( $object->term_id,$taxonomy );
$result = (array) term_exists( $category,$taxonomy );
if( ! empty( $result ) ) {
return false;
}
return in_array( reset($result),$children );
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。
用法:
if ( is_maybe_child_product_category( 'laptop' ) ) {
// Do something
}
,
您可以使用 term_is_ancestor_of()
检查正在查看的当前术语(产品类别)是否属于父术语。
我写了一个简单的辅助函数:
/**
* @param int|object $parent ID or object term object to check.
* @return bool Whether the product category being viewed is a child of the given parent category.
*/
function wpse_is_child_product_category( $parent ) {
if ( ! is_product_category() ) {
return false;
}
return term_is_ancestor_of( $parent,get_queried_object(),'product_category' );
}
用法:
if ( is_product_category( 5 ) || wpse_is_child_product_category( 5 ) ) {
// . . .
,
使用以下行:
is_product_category( array( 'electronic','mobile','laptop' ) )