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

Hide completely from anywhere on my site any product that has no category. : wooCommerce

在我的 wooCommerce 平台中,我不想显示没有选择类别的产品。我的意思是哪些产品类别为空,即产品未显示在我的站点中。 有什么办法吗?

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

WP_Query

您可以连接到 pre_get_posts 操作并修改 tax_query arg 以排除 uncategorized 产品类别中的产品(仅当查询 post 类型是 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)。您可能需要检查您网站的所有页面,看看您是否涵盖了所有页面。