简体   繁体   English

如何在woocommerce商店页面中隐藏同名产品?

[英]How to hide same name products in woocommerce shop page?

I am creating an E commerce website.我正在创建一个电子商务网站。 On that website I added many products.在那个网站上,我添加了许多产品。 Some products have same name, but I want to hide same name products in shop page.有些产品同名,但我想在商店页面隐藏同名产品。
Eg:- There is a product named " ABC " and with the name of " ABC " product.例如:-有一个名为“ ABC ”且名称为“ ABC ”的产品。 There are many products are added but sku is different, so in Shop page, I just want to show only one product which have same name products.添加了很多产品但sku不同,所以在Shop页面中,我只想显示一个具有相同名称产品的产品。

archive-product.php :存档-product.php :

$pn[0] = 'demo';
$i = 0;
while (have_posts()) {
  the_post();
  do_action('woocommerce_shop_loop');
  global $product;
  $pr = $product->get_name();
  $j = 0;
  $ps = sizeof($pn);
  $a = 1;
  while ($j <= $ps) {
    if ($pn[$j] == $pr) {
      $a = 0;
      break;
    }
    $j++;
  }
  if ($a != 0) {
    $i++;
    $pn[$i] = $pr;
    wc_get_template_part('content', 'product', $rst);
  }
}

This code works fine, but issue is in pagination .这段代码工作正常,但问题在于分页 In page 1 it only shows 1 product and hides all other products with same name but other name products it will show in 2nd page of pagination, that products will be not shows on page 1.在第 1 页中,它只显示 1 个产品并隐藏所有其他同名产品,但其他名称的产品将显示在分页的第 2 页中,该产品不会显示在第 1 页上。
And I also don't want to make same name products private or unlisted.而且我也不想将同名产品设为私有或不公开。

You can do it with WP_QUERY's posts_distinct filter.您可以使用 WP_QUERY 的 posts_distinct 过滤器来实现。 (revert back your template's while loop's code) (恢复模板的 while 循环代码)

add_filter( 'posts_distinct', function ( $distinct ) {
    if ( is_admin())return $distinct;
    //i have added just one is_admin exception,
    //but you can add there another conditions as well
    return 'DISTINCT';
});

I had the same problem and i've managed to do it with a function.我遇到了同样的问题,我已经设法用一个函数来做到这一点。 This fuction hides same title products in shop page, in category and in search results.此功能会在商店页面、类别和搜索结果中隐藏相同标题的产品。

Try this:尝试这个:

add_filter( 'posts_groupby', 'custom_posts_groupby', 10, 2 );
function custom_posts_groupby( $groupby, $query ) {
     global $wpdb;

     if ( is_main_query() && (is_shop() || is_product_category() || is_search() )) {
         $groupby = "{$wpdb->posts}.post_title";
     }

     return $groupby;
}

You can see my question here https://stackoverflow.com/a/60837657/10183871你可以在这里看到我的问题https://stackoverflow.com/a/60837657/10183871

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM