Woocommerce 仅向特定类别和特定页面中的产品添加自定义产品计数

Woocommerce adding custom product count to products only in specific category and in specific page

我已经掌握了一些逻辑,但还在为如何实现而苦恼:

我在 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 函数?

试试这个。在以下函数中使用相应的类别名称和自定义 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++;
}

希望对您有所帮助。

您需要使用 is_page and has_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: 未经测试的代码。