-1

In wordpress i am creating a custom loop/query throughwhich i pass certain parameters. As i click through pages however the last page duplicates some posts/products inorder to satisfy the posts_per_page variable however i would like to specify that i dont want any repetitions. Is there a standard way to do this? It would seem like a pretty obvious point.

  <?php

        $args = array( 'post_type' => 'product', 'posts_per_page' => 5, 'product_cat' => 'products', 'orderby' => 'rand' );
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); global $product;  ?>
           <li class="product">    

                    <a href="<?php echo get_permalink( $loop->post->ID ) ?>" title="<?php echo esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID); ?>">

                        <?php woocommerce_show_product_sale_flash( $post, $product ); ?>

                        <?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); else echo '<img src="'.woocommerce_placeholder_img_src().'" alt="Placeholder" width="300px" height="300px" />'; ?>

                        <h3><?php the_title(); ?></h3>

                        <span class="price"><?php echo $product->get_price_html(); ?></span>                    

                    </a>

                    <?php woocommerce_template_loop_add_to_cart( $loop->post, $product );  ?>

                </li>

    <?php endwhile; ?>


   <?php previous_posts_link('&laquo; Previous', $loop ->max_num_pages);
next_posts_link(' Next &raquo;', $loop ->max_num_pages); ?>
    <?php wp_reset_query();?>
Maximilian Travis
  • 311
  • 1
  • 3
  • 12

1 Answers1

1

It would seem like a pretty obvious point.

Not if you're using 'orderby' => 'rand' on your query, which is also very expensive by the way on large tables.

If you want to make sure that the items which already have been displayed will be excluded in the upcoming queries you'll need to save the post_ids which already has been displayed and pass them to the post__not_in parameter, see the codex page an search for post__not_in .

You could do something like this which should help you get the idea:

...
// don't forget to initialize the session somewhere

$already_displayed_post_ids = [];

if ( ! isset( $_SESSION['already_displayed_post_ids'] ) {
  $_SESSION['already_displayed_post_ids'] = $already_displayed_post_ids;
} else {
  $already_displayed_post_ids = array_merge( $already_displayed_post_ids, $_SESSION['already_displayed_post_ids'] );
}

$args = [
  'post_type' => 'product',
  'posts_per_page' => 5,
  'product_cat' => 'products',
  'orderby' => 'rand',
  'post__not_in' => $already_displayed_post_ids
];

$loop = new WP_Query( $args );
...
miron
  • 1,361
  • 1
  • 11
  • 24