• Resolved dlsn

    (@dlsn)


    Hello!

    I want to show max. 2 sticky posts on my blog in a specific loop. But if there is only one or no sticky post, the loop shouldn’t show “normal”posts.

    But the following code shows “normal” posts if there are not 2 or more sticky posts:

    $args   = array(
            'numberposts'         => 2,
    	'post__in'            => get_option( 'sticky_posts'),
    	'ignore_sticky_posts' => 1
            );
    $sticky_posts = get_posts( $args );

    Thank you a lot in advance!
    Daniel

    • This topic was modified 1 year, 9 months ago by dlsn.
Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    “numberposts” has been deprecated, please use “posts_per_page” instead.

    When you pass an empty array (no stickies) as ‘post__in’, the entire query var is ignored and you’ll get the 2 latest posts instead. To avoid this, get the sticky_posts option before doing anything. If the array length is 0, skip over the entire process (query and loop). Otherwise use the returned array as the ‘post__in’ arg.

    Thread Starter dlsn

    (@dlsn)

    Thank you very much @bcworkz ! It works! Great!

    For others who are interesed, this is my working snippet for this function.

    if(count(get_option('sticky_posts'))>1){
            $args   = array(
                    'posts_per_page'         => 2,
                    'post__in'            => get_option( 'sticky_posts' ),
                    'ignore_sticky_posts' => 1
            );
            $sticky_posts = get_posts( $args );
    }elseif(count(get_option('sticky_posts'))>0){
            $args   = array(
                    'posts_per_page'         => 1,
                    'post__in'            => get_option( 'sticky_posts' ),
                    'ignore_sticky_posts' => 1
            );
            $sticky_posts = get_posts( $args );
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Query only sticky posts (without “normal” posts)’ is closed to new replies.