11

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) :
            ?>

3 Answers 3

36

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);
7
  • @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, 2011 at 17:38
  • Try the latest edit. Populate your arguments into an array. Sep 19, 2011 at 18:01
  • 1
    Hm? Why me? @Brian Fegter answered. :)
    – kaiser
    Sep 19, 2011 at 18:08
  • ha :) I'm good. Always glad to help out. Sep 19, 2011 at 18:22
  • Perfect, thanks everyone especially @BrianFegter !
    – Chad
    Sep 21, 2011 at 3:53
3

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.

1

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' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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