Question

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) :
            ?>
Était-ce utile?

La solution

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

Autres conseils

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.

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' );
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top