在我的网站上的任何地方完全隐藏任何没有类别的产品.:wooCommerce



在我的wooCommerce平台中,我不想显示没有选择类别的产品。我的意思是,哪些产品类别是空的,哪些产品没有显示在我的网站上。有办法做到这一点吗?

检索products有不同的方法,如果您想从站点中的任何位置排除未分配类别的产品,则需要解决所有这些问题。

WP_Query

您可以挂接到pre_get_posts操作并修改tax_query参数,以便排除uncategorized产品类别中的产品(仅当查询帖子类型为product时(。事实上,我假设uncategorized是默认产品类别的slug(您需要将其修改为您的特定配置(。例如:

function remove_uncategorized_products( $query ) {
if ( is_admin() ) {
return;
}
if ( 'product' !== $query->get( 'post_type' ) ) {
return;
}
$tax_query = (array) $query->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'uncategorized' ),
'operator' => 'NOT IN',
);
$query->set( 'tax_query', $tax_query );
}
add_action( 'pre_get_posts', 'remove_uncategorized_products' );

WC_Query

与WP_Query类似,您可以挂接woocommerce_product_query操作来修改查询。例如:

function custom_pre_get_posts_query( $q ) {
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'uncategorized' ),
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );

WC_Product_Query(由WC_get_products使用(

在这种情况下,我们不能更改查询参数以排除某些产品类别。相反,我们可以循环查询返回的每个产品,并检查其类别。例如:

function filter_uncategorized_products_out( $results, $args ) {
$products = array();
foreach ( $results as $p ) {
$is_uncategorized = false;
$terms = get_the_terms( $p->get_id(), 'product_cat' );
foreach ( $terms as $term ) {
if ( 'uncategorized' === $term->slug ) {
$is_uncategorized = true;
}
}
if ( ! $is_uncategorized ) {
$products[] = $p;
}
}
return $products;
}
add_filter( 'woocommerce_product_object_query', 'filter_uncategorized_products_out', 10, 2 );

请注意,还有其他方法可以检索产品(例如,直接使用$wpdb(。你可能需要检查你网站的所有页面,看看你是否已经涵盖了所有页面。

最新更新