我正在使用需要在不同类别页面上显示特定内容的代码。
我的类别有一个结构:
男人
但是我的代码仅在父类别(男士)和第一级子类别(布料)上显示内容。
如何强制它显示较低级别子类别的内容?例如,在“短裤”和“带口袋的短裤”中。 (可能更低)
请帮忙
add_action( 'woocommerce_archive_description', 'add_slide_text',1 );
function add_slide_text() {
$cat = get_queried_object();
if ( is_product_category() ) {
if ( is_product_category( 'man' ) || $cat->parent === 233 ) {
echo 'Hello man';
} elseif ( is_product_category( 'woman' ) || $cat->parent === 232 ) {
echo 'Hello woman';
} else {
echo '';
}
}
}
您可以使用WordPress功能
cat_is_ancestor_of()
。
查看此处的文档:https://developer.wordpress.org/reference/functions/cat_is_ancestor_of/
基本上,您给它两件事:您认为是父类别的内容和您期望成为子类别的内容。
无论层次有多深,它都会返回true。
以下是如何使其发挥作用的简单示例:
$current_category = get_queried_object();
$man_category_id = get_cat_ID('Man');
// Check if the current category or its ancestors include the "Man" category
if (cat_is_ancestor_of($man_category_id, $current_category->term_id)) {
echo "Display your content here";
}
请注意,我尚未测试此代码,因此请随意调整它以适合您的情况。
您可以使用
get_term_children()
显示 2 个特定产品类别术语及其子术语的特定文本,如下所示:
add_action( 'woocommerce_archive_description', 'add_slide_text', 1 );
function add_slide_text() {
if ( is_product_category() ) {
$term = get_queried_object();
// Man (and term ID 233)
$term1 = get_term_by('slug', 'man', $term->taxonomy);
$children1_ids = (array) get_term_children($term1->term_id, $term->taxonomy);
$term1_ids = array_merge( array(233, $term1->term_id), $children1_ids );
// Woman (and term ID 232)
$term2 = get_term_by('slug', 'woman', $term->taxonomy);
$children2_ids = (array) get_term_children($term1->term_id, $term->taxonomy);
$term2_ids = array_merge( array(232, $term1->term_id), $children1_ids );
if ( in_array( $term->term_id, $term1_ids ) ) {
echo 'Hello man';
} elseif ( in_array( $term->term_id, $term2_ids ) ) {
echo 'Hello woman';
}
}
}
应该可以。