Duplicate posts

You can use a static class property to store a rolling list of posts that are used in previous queries. This method allows you to pass data between classes (widgets, modules, plugins, etc…), but will also work for a procedural workflow. Everything on the page that uses your intermediary class will know what posts to exclude.

Step 1: Create a class that has a static $posts property

You will need getter and setter methods.

class RollingPostsIndex{
    public static $posts = array();

    public function set($new_posts){
        $previous_posts = self::get();
        $posts = array_push($previous_posts, $new_posts);
        return self::$posts = $posts;
    }

    public function get(){
        return self::$posts;
    }
}

Step 2: Create two helper functions to for setting and getting.

function add_rolling_posts($post_ids);
    RollingPostsIndex::set($post_ids);
}

function get_rolling_posts(){
    return RollingPostsIndex::get();
}

Step 3: Track your post ids within your WP_Query instance loops

$post_ids[] = $post->ID;

Step 4: Add the new section post IDs array to the RollingPostsIndex static property

Use the API function we created earlier.

add_rolling_posts($post_ids);

Step 4: Add an argument to your WP_Query instance to exclude previously used post ids.

$args['__post_not_in'] = get_rolling_posts();

I’ve tested this method extensively, and it works really well to keep track of post ids throughout the entire page load.

Hope this helps you out!

Leave a Comment