what would be the best way to exclude the current post I am viewing from this recent posts query. Thank You!

<?php
            global $post;
            if (in_category('top-lists')) {
                $myposts2 = get_posts('numberposts=5&offset=0&category=7');
            }
            else if (in_category('playlists') || in_category('playlistall')) {
                $myposts2 = get_posts('numberposts=5&offset=0&category=6,37');
            }
            else if (in_category('news') || in_category('news')) {
                    $myposts2 = get_posts('numberposts=5&offset=0&category=95');
            }
            else {
                $myposts2 = get_posts('numberposts=5&offset=0&category=-6,-7,-37,-95,-177');
            }

            foreach($myposts2 as $post) :
            ?>
up vote 17 down vote accepted

This the post__not_in arg should work dandy for you:

$args = array(
    'numberposts' => 5,
    'offset' => 0,
    'category' => 7,
    'post__not_in' => array( $post->ID )
);
$myposts2 = get_posts($args);
  • @kaiser and Brian - Thanks for getting back to me, I put in the code but I am getting a map_array error ---- Warning: array_map() [function.array-map]: Argument #2 should be an array in /home/sitemain/public_html/wp-includes/query.php on line 1709 Warning: implode() [function.implode]: Invalid arguments passed in /home/sitemain/public_html/wp-includes/query.php on line 1709 – Chad Sep 19 '11 at 17:38
  • Try the latest edit. Populate your arguments into an array. – Brian Fegter Sep 19 '11 at 18:01
  • 1
    Hm? Why me? @Brian Fegter answered. :) – kaiser Sep 19 '11 at 18:08
  • ha :) I'm good. Always glad to help out. – Brian Fegter Sep 19 '11 at 18:22
  • Perfect, thanks everyone especially @BrianFegter ! – Chad Sep 21 '11 at 3:53

Add below code in active theme functions.php file

    function be_exclude_current_post( $args ) {
        if( is_singular() && !isset( $args['post__in'] ) )
            $args['post__not_in'] = array( get_the_ID() );
        return $args;
    }
    add_filter( 'widget_posts_args', 'be_exclude_current_post' );

Add this to your $args

'post__not_in' => array( get_the_ID() )

This way you won't have to deal with getting the current post ID and will potentially avoid errors with getting your ID. The get_the_ID() function just get the ID for you so you don't have to deal with or do anything.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.