0

I have the following query, trying to fetch the latest sticky posts but exclude the current one:

$sticky = get_option('sticky_posts');
rsort( $sticky );
$sticky = array_slice($sticky, 0, 3);

query_posts(
    array(
        'post__not_in' => array($post->ID),
        'post__in' => $sticky,
        'caller_get_posts' => 1,
    )
);

Getting the posts works fine, but post__not_in doesn't. Is there an effective way to do this?

2
  • 3
    Read this. Note: you cannot combine post__in and post__not_in in the same query.
    – tfrommen
    Commented Apr 18, 2013 at 23:16
  • And this. Commented Apr 18, 2013 at 23:17

1 Answer 1

2

This should do:

// Get sticky posts
$sticky = get_option('sticky_posts');
rsort($sticky);
$sticky = array_slice($sticky, 0, 3);

// Check if current post is inside
foreach ($sticky as $key => $value)
    if ($value === $GLOBALS['post']->ID) {
        // ... and remove
        unset($sticky[$key]);
        break;
    }

$query = new WP_Query(
    array(
        'post__in' => $sticky,
        'ignore_sticky_posts' => 1,
    )
);

If you want to have 3 posts (no matter what), you have to do it like so (minimally changed):

// Get sticky posts
$sticky = get_option('sticky_posts');
rsort($sticky);

// Check if current post is inside
foreach ($sticky as $key => $value)
    if ($value === $GLOBALS['post']->ID) {
        // ... and remove
        unset($sticky[$key]);
        break;
    }

$sticky = array_slice($sticky, 0, 3);

$query = new WP_Query(
    array(
        'post__in' => $sticky,
        'ignore_sticky_posts' => 1,
    )
);

// EDIT: added break after current post ID has been found and removed, in case you have a great number of sticky posts.

1
  • 1
    Works like charm :D Thanks alot for the effort and patience
    – user23068
    Commented Apr 19, 2013 at 12:10

Your Answer

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