【问题标题】:Show products out of stock in a category显示某个类别中缺货的产品
【发布时间】:2023-03-16 03:11:01
【问题描述】:

在 WooCommerce 中,我已选中“可见性缺货”选项,但我需要某些产品类别保持可见,即使该选项已选中。

另一方面,主商店不显示该类别。为此,我使用了以下代码:

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {

  if ( ! $q->is_main_query() ) return;
  if ( ! $q->is_post_type_archive() ) return;  
  if ( ! is_admin() && is_shop() ) {

  $q->set( 'tax_query', array(array(
      'taxonomy' => 'product_cat',
      'field' => 'slug',
      'terms' => array( 'MYCATEGORY' ), // Don't show this category.
      'operator' => 'NOT IN'
  )));  
  }

  remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}

因为有可能这样做吗?

谢谢!

【问题讨论】:

    标签: php wordpress woocommerce categories product


    【解决方案1】:

    这只是一个简单的猜测,未经测试,但您可以尝试从以下内容开始:

    global $product;
    
    $terms = wp_get_post_terms( $post->ID, 'product_cat' );
    foreach ( $terms as $term ) $categories[] = $term->slug;
    
    $category_to_show = ‘MYCATEGORY’;
    if( $categories ) {
        if( in_array( $category_to_show, $categories ) && !$product->is_in_stock() ) {
            apply_filters( 'woocommerce_product_is_visible', true, $product->id );
        }
    }
    

    【讨论】:

    • 这是在循环中使用的?
    • 您应该能够通过删除 post->ID 在函数文件中的函数中使用它。然后你可以使用 $terms = wp_get_post_terms( $taxonomy = 'product_cat' );如果没有,请尝试在循环中使用它,例如 content-product.php,您可以删除全局产品,因为它已经包含在该文件中
    • 这给我一个错误Warning: in_array() expects parameter 2 to be array, null given in /functions.php on line 344 这一行是这样的:if( in_array( $category_to_show, $categories ) && !$product->is_in_stock() ) { 错误在哪里?我找不到这个...
    • 错误是因为类别数组是空的,它不能在NULL上迭代。你可以尝试用 if( $categories ) 包装 if( in array ... : if( in_array.. etc
    • 对不起,我写 php.ini 太糟糕了。请问,你能用解决方案编辑第一条评论吗?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2011-05-26
    • 2021-06-15
    相关资源
    最近更新 更多