【问题标题】:Redirect Custom Page If the Product Count is Zero in a Woocommerce Category如果 Woocommerce 类别中的产品计数为零,则重定向自定义页面
【发布时间】:2020-05-09 17:44:07
【问题描述】:

如果 Woocommerce 类别中的产品计数为零,我需要重定向自定义页面请帮助我

【问题讨论】:

    标签: javascript wordpress woocommerce hook-woocommerce


    【解决方案1】:

    假设您通过分类术语页面之一访问产品类别:

    将此添加到您的functions.php 文件中。确保将 SOME_PATH . '/some-custom-file.php'; 替换为您要加载的模板的路径。

    add_filter( 'template_include', 'redirect_on_empty_product_category' );
    
    function redirect_on_empty_product_category( $template ){
    
      if ( ( $taxonomy_id = get_query_var( 'taxonomy' ) ) && ( $term_id = get_query_var( 'term' ) ) && is_tax( $taxonomy_id, $term_id ) ){
    
        $term = get_term_by( 'slug', $term_id, $taxonomy_id );
    
        if ( $term->count === 0 ){
          $page_url = get_permalink($some_post_id);
          echo sprintf('<script type="text/javascript"> window.location = "%s" </script>', $page_url);
        }
      }
    
      return $template;
    }
    

    【讨论】:

    • 嗨,我可以使用页面 id 或 slug 重定向到自定义页面,而不是某些模板
    • 当然,请参阅我对您的编辑的编辑,我添加了$page_url = get_permalink($some_post_id); 并将您的 echo 语句转换为 sprintf 以提高可读性。只要确保$some_post_id 是一个真实的页面ID
    【解决方案2】:

    您只需添加 $cat->count 即可获取该类别中所有产品的计数。希望对您有所帮助。

    $args = array(
        'number'     => $number,
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
        'include'    => $ids
    );
    
    $product_categories = get_terms( 'product_cat', $args );
    
    foreach( $product_categories as $cat )  { 
       echo $cat->name.' ('.$cat->count.')'; 
    }
    

    谢谢

    【讨论】:

      猜你喜欢
      • 2016-07-16
      • 2020-10-18
      • 1970-01-01
      • 2021-02-25
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多