SPL Design

Just another London based print & web designer.

 instagram |  twitter |  pintrest|  linkedin

WordPress Custom Archive.php – Get Sticky Posts Of Current Category before All Posts

Client Request:
Sticky Posts on certain pages

Sticky Posts Overview:
In terms of theming, a sticky post is a regular post that “will be placed at the top of the front page of posts, keeping it there until new posts are published”.

Notes: Won’t work on custom post types, sticky posts don’t display on all themes at the top of the archive.php (archive pages). So if you run a blog and want to use the sticky post to feature a post, i.e. always show in the first position, it will on the home page of most themes, but not on your archive pages, or anywhere else (unless you explicitly query only sticky posts.

References: WordPress Sticky Post Codex

Site Structure:

The “sticky posts” would need to be displayed on some archive.php pages and some page.php pages.

We decided to use the built in WordPress “Sticky Post” functionality.

Step 1: Displaying ONLY sticky posts from the current category on the archive.php

This means that if there are no sticky posts in the current category you are browsing, no posts will show up.

Add the following to your functions.php

/*sticky categories*/

add_action( 'pre_get_posts', function( \WP_Query $q )
    if( ! is_admin() && $q->is_category() && $q->is_main_query() )
        $sticky_posts = get_option( 'sticky_posts' );
        if( ! empty( $sticky_posts ) )
            $q->set( 'post__in', (array) $sticky_posts );
} );

Now add this to your archive.php or what ever page you are using to display your sticky posts. This is now going to call all sticky posts from the current category

//Get Sticky Posts for Current Cat

     get_option( 'sticky_posts' ),
            'posts_per_page'      => 3,
            'ignore_sticky_posts' => true,
	    'cat' => get_query_var('cat') 
        ) );

        while ( $sticky->have_posts() ) : $sticky->the_post();


// Stumptown pitchfork microdosing listicle, kickstarter subway tile tote bag butcher vinyl //

Now you want all the other posts, an archive would be pretty useless without stuff archived on it, and if there are no sticky posts in the current category it would be blank. 

Return ALL posts within the category, but don't show sticky posts at the top. The 'sticky posts' will still show in their natural position

//Get The Other Posts, show the sticky in their natural order_by position

	'cat' => get_query_var('cat') 
         ) );

        while ( $arch->have_posts() ) : $arch->the_post(); ?>