【问题标题】:Woocommerce adding custom product count to products only in specific category and in specific pageWoocommerce 仅在特定类别和特定页面中向产品添加自定义产品计数
【发布时间】:2016-07-16 17:01:57
【问题描述】:

我已经掌握了一些逻辑,但正在与如何实施作斗争:

  • 仅在特定产品类别中的产品上显示我的自定义产品计数
  • 还仅在特定的自定义 WP 页面上显示产品数量(我使用了 product_category 短代码)

我在functions.php中的代码如下,它确实在产品缩略图之前添加了$top50_counter值,但它是在整个站点范围内进行的,因此为什么我需要根据上述观点缩小范围。

/* ADD NUMBERING TO TOP 50 LIST PRODUCTS */
add_action( 'woocommerce_before_shop_loop_item_title', 'custom_before_shop_loop_item', 5);
$top50_counter=1;
function custom_before_shop_loop_item() {
  global $top50_counter;

  echo '<h1>'.$top50_counter.'</h1>';
  $top50_counter++;
}

我假设我必须以某种方式使用其中的$terms = get_the_terms 函数?

【问题讨论】:

    标签: woocommerce counter categories product shortcode


    【解决方案1】:

    您需要使用is_pagehas_term 条件。尝试将代码重构为以下内容。

    /* ADD NUMBERING TO TOP 50 LIST PRODUCTS */
    add_action( 'woocommerce_before_shop_loop_item_title', 'custom_before_shop_loop_item', 5);
    
    $top50_counter=1;
    
    function custom_before_shop_loop_item() {
    
      global $top50_counter;
    
      /* Replace 42 with the actual page ID and "your-category" with the actual category slug */
    
      if( ( is_page( 42 ) ) || ( has_term( 'your-category' , 'product_cat') ) ):
          echo '<h1>'.$top50_counter.'</h1>';
          $top50_counter++;
    
      endif;
    }
    

    P.S:未经测试的代码。

    【讨论】:

    • 阿南德,谢谢。我在您的代码中发现的唯一逻辑问题是 IF 是逻辑 OR 的 || 应该是逻辑 AND &amp;&amp; 因为如果它是 OR,它将激活其他页面上的编号代码。我会将您的答案标记为已接受。谢谢,感谢,我今天学到了一些东西。
    • 我很高兴能帮上忙。我最初使用&amp;&amp;,但在重新阅读您的问题后有点困惑并将其更改为逻辑或,请参阅我的编辑:)
    【解决方案2】:

    试试这个。在以下函数中使用对应的类别名称和自定义 wp 页面 slug。

    function custom_before_shop_loop_item(){
        global $post, $term, $top50_counter;
        $id = $post->ID;
        $taxonomy = 'product_cat';
        $terms = get_the_terms( $id, $taxonomy );
        if( ($terms[0]->name == 'Category Name') || ($post->post_name == 'custom-wp-page-slug') ){
            echo '<h1>'.$top50_counter.'</h1>';
        }
        $top50_counter++;
    }
    

    希望这会有所帮助。

    【讨论】:

    • 如果成功,get_the_terms 将返回一个数组,因此$terms-&gt;name 将不起作用。修复您的代码以在循环中运行if 检查foreach( $terms as $term ) { if( $term-&gt;name == 'Category Name' ..... 此外$top50_counter++ 应该在if 条件内,仅当产品具有该特定类别时才增加它。
    • 谢谢你们,解决问题的所有变体,对我来说更有意义,我学到了一些东西。我已将第一个答案标记为已接受,尽管我确信您的代码也可以使用。赞赏。
    猜你喜欢
    • 1970-01-01
    • 2018-04-30
    • 2023-04-08
    • 2021-01-29
    • 2020-10-18
    • 2018-07-07
    • 1970-01-01
    • 2022-01-22
    • 2016-08-06
    相关资源
    最近更新 更多