Exclude Current and Sticky Post

On a single Post page I have a side bar displaying up to three other, related posts. How can I exclude both Sticky Posts and the Current post?

I know how to exclude the Current post and how to exclude Sticky Posts by using post_not_in in a WP_Query, see code example below. But I guess you can not use post_not_in twice in the same query. Any suggestions?

$current_post_ID = get_the_ID();

        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'order' => 'DESC',
            'orderby' => 'date',
            'posts_per_page' => 3,
            'post__not_in' => get_option( 'sticky_posts' )
            'post__not_in' => array($current_post_ID)
        );

Related posts

Leave a Reply

2 comments

  1. Whenever an array of arguments is a function parameter in a WP core function it is parsed via wp_parse_args and almost always extracted into single variables.
    I.e. no, you cannot use the same argument twice.

    What you want to do is something like this:

    $exclude = get_option( 'sticky_posts' );
    $exclude[] = get_the_ID();
    
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'order' => 'DESC',
        'orderby' => 'date',
        'posts_per_page' => 3,
        'post__not_in' => $exclude
    );
    

    As an aside, you were also missing a comma.

  2. You should add the current post’s ID to the array of IDs of your sticky posts, and pass this single array to post__not_in:

    $current_post_ID = get_the_ID();
    
    $excluded_ids = get_option( 'sticky_posts' );
    $excluded_ids[] = $current_post_ID;
    
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'order' => 'DESC',
        'orderby' => 'date',
        'posts_per_page' => 3,
        'post__not_in' => $excluded_ids
    );
    

    Also note that you didn’t type a comma after your first post__not_in. That might cause problems as the second instance of post__not_in isn’t recognized as another element of the array.