Skip to content

Instantly share code, notes, and snippets.

@solepixel
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solepixel/0da3c26e526a959da894 to your computer and use it in GitHub Desktop.
Save solepixel/0da3c26e526a959da894 to your computer and use it in GitHub Desktop.
This little snippet will consistently place sticky posts at the top of ALL post archive pages, not just the first page.
<?php
add_filter( 'the_posts', 'mytheme_inject_sticky_posts', 10, 2 );
function mytheme_inject_sticky_posts( $posts, $q ){
// Don't do this in the admin or on page 1, WP already does it for page 1
if( is_admin() || $q->get( 'paged' ) <= 1 )
return $posts;
// get the sticky posts array
$sticky_posts = get_option( 'sticky_posts' );
if( ! $sticky_posts )
return $posts;
/**
* This condition could vary. In my case, this determined if we were viewing the blog archive.
*/
if( $q->get( 'pagename' ) == 'blog' ){
// this chunk is pretty much straight out of WP_Query
$num_posts = count( $posts );
$sticky_offset = 0;
$stickies = get_posts( array(
'post__in' => $sticky_posts,
'post_type' => 'post', // just in case we have other types of sticky posts
'post_status' => 'publish',
'nopaging' => true
) );
foreach ( $stickies as $sticky_post ) {
array_splice( $posts, $sticky_offset, 0, array( $sticky_post ) );
$sticky_offset++;
}
}
return $posts;
}
add_filter( 'post_class', 'mytheme_add_sticky_class' );
/**
* Be sure to add the sticky class to the post
*/
function mytheme_add_sticky_class( $classes ){
$sticky_class = 'sticky';
$sticky_posts = get_option( 'sticky_posts' );
if( in_array( get_the_ID(), $sticky_posts ) ){
if( ! in_array( $sticky_class, $classes ) ){
$classes[] = $sticky_class;
}
}
return $classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment