On my WordPress site, I have a CSS grid. In the grid are several blocks that each use query loops to pull post titles, etc. The query loops are set to order by random. However, I get duplicate posts in the grid when I select random. What would be the best method to ensure I don’t get any duplicate posts in the grid?
I’ve tried all kinds of code, arrays, transients, but I must be the worst because nothing I’ve tried works. I don’t even know what method is best or if I should abandon this idea altogether.
This was the last query loop I tried:
$excluded_ids = get_transient('excluded_post_ids');// Query argumentsreturn $args = array( 'post_type' => 'post', 'posts_per_page' => 1, 'orderby' => 'rand', 'post__not_in' => $excluded_ids // Exclude already displayed posts);$query = new WP_Query($args);if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); the_content(); }}wp_reset_postdata();
These are the PHP I tried:
<?php// Get the list of excluded post IDs from a transient$excluded_ids = get_transient('excluded_post_ids');// If transient doesn't exist, initialize as an empty arrayif ($excluded_ids === false) { $excluded_ids = array();}?>
<?php// Function to initialize and fetch unique post IDsfunction initialize_and_fetch_posts() { // Get excluded post IDs $excluded_ids = get_transient('excluded_post_ids'); if ($excluded_ids === false) { $excluded_ids = array(); } $block_queries = array(); // Loop through each block for ($i = 1; $i <= 7; $i++) { $query_args = array( 'post_type' => 'post', 'posts_per_page' => 1, 'fields' => 'ids', 'post__not_in' => $excluded_ids, // Exclude already displayed posts 'orderby' => 'rand' ); $query = new WP_Query($query_args); // Add current post IDs to excluded list $excluded_ids = array_merge($excluded_ids, $query->posts); $block_queries[$i] = $query->posts; } // Store updated excluded IDs in transient set_transient('excluded_post_ids', $excluded_ids, 6); return $block_queries;}?>