How to make WordPress sticky posts work in custom loops?

I want to be able to create custom loops using query_posts or $custom_query = new WP_Query()
and be able to make sticky posts.

For example I have a custom loop on a page called News, which loops the posts in ‘news’ -category and builds a nice Masonry grid out of them. The looped items then link to the actual article.

Read More
<?php $custom_query = new WP_Query('cat=8'); // boxes loop
        while($custom_query->have_posts()) : $custom_query->the_post(); ?>
        <div <?php post_class('newsbox box '); ?> id="post-<?php the_ID(); ?>">
            <?php  //if looplink exists, looplink
                $looplink = get_post_meta( get_the_ID(), 'linkki', true );
                if( ! empty( $looplink ) ) :?> <a class="looplink" target="_blank" href="<?php $linkki = get_post_meta($id, 'linkki', true ); if( ! empty( $linkki ) ) { echo $linkki; } ?>"></a>
            <?php endif; //end looplink ?>
            <h3><?php the_title(); ?></h3>
            <?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>
            <?php the_content(); ?>
        </div>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); // reset the query ?>

I’m also using this loop to display i.e. social media widgets, so these should always be the first couple of articles (=sticky).

One idea which I’m not totally satisfied with is to not specif a category to loop, but specifying the unwanted categories to exclude. It seems to make Sticky Posts work for some reason. Is there a way to make this work with some simple function without having to

query_posts('cat=-1,-2,-3,-4');

etc for all the loops?

Of course a solution that would make the Sticky posts always sticky, no matter if I’m using them in the home page or custom loop showing a specfic category or wherever.

Related posts

Leave a Reply

1 comment

  1. This excludes all the sticky posts.

    query_posts( array( 'post__not_in' => get_option( 'sticky_posts' ) ) );
    

    To include sticky posts:

        $args = array(
        'posts_per_page' => 1,
        'post__in'  => get_option( 'sticky_posts' ),
        'ignore_sticky_posts' => 1
    );
    query_posts( $args );
    

    ignore_sticky_posts : ignore sticky posts or not (available with Version 3.1, replaced caller_get_posts parameter). Default value is 0 – don’t ignore sticky posts. Note: ignore/exclude sticky posts being included at the beginning of posts returned, but the sticky post will still be returned in the natural order of that list of posts returned.