简体   繁体   中英

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. 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.

archive-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.
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. (revert back your template's while loop's code)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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