我有两个产品类别
多语言数字营销(ID 75)
国际销售渠道(ID 107)我只想通过if条件为这两个类别运行一些代码。
我试着使用这个代码,但没有成功
if( is_product_category(107 || 75) ) {
$term = get_queried_object();
$parent = $term->parent;
if (!empty($parent)) {
$child_of = $parent;
} else {
$child_of = $term->term_id;
}
$terms = get_terms( array(
\'taxonomy\' => \'product_cat\',
\'child_of\' => $child_of,
) );
if ($terms) {
foreach ( $terms as $category ) {
$category_id = $category->term_id;
$category_slug = $category->slug;
$category_name = $category->name;
$category_desc = $category->description;
echo \'<div class="\'.$category_slug.\'">\';
echo \'<h2>\'.$category_name.\'</h2>\';
if ($category_desc) {
echo \'<p>\'.$category_desc.\'</p>\';
}
$products_args = array(
\'post_type\' => \'product\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'term_id\',
\'terms\' => $category_id,
),
),
);
$products = new WP_Query( $products_args );
if ( $products->have_posts() ) { // only start if we hace some products
// START some normal woocommerce loop
woocommerce_product_loop_start();
if ( wc_get_loop_prop( \'total\' ) ) {
while ( $products->have_posts() ) : $products->the_post();
/**
* Hook: woocommerce_shop_loop.
*
* @hooked WC_Structured_Data::generate_product_data() - 10
*/
do_action( \'woocommerce_shop_loop\' );
wc_get_template_part( \'content\', \'product\' );
endwhile; // end of the loop.
}
woocommerce_product_loop_end();
// END the normal woocommerce loop
// Restore original post data, maybe not needed here (in a plugin it might be necessary)
wp_reset_postdata();
}
最合适的回答,由SO网友:Kanon Chowdhury 整理而成
is_product_category()
仅在woocommerce类别存档页面上使用,因此首先确保您处于类别存档中。
使用类别段塞名称代替类别编号is_product_category(\'category-slug\')
无需运行或(| |)条件,只需使用is_product_category(\'category-slug1\',\'category-slug2\')
获得相同的输出