Skip to content

Instantly share code, notes, and snippets.

@shazdeh
Created December 13, 2013 19:13
Show Gist options
  • Save shazdeh/7949549 to your computer and use it in GitHub Desktop.
Save shazdeh/7949549 to your computer and use it in GitHub Desktop.
Respect sticky posts in category requests
<?php
function putStickyOnTop( $posts ) {
global $wp_query;
if( $wp_query->is_category() ){
$sticky_posts = get_option('sticky_posts');
$num_posts = count( $posts );
$sticky_offset = 0;
//loop over posts and relocate stickies to the front
for( $i = 0; $i<$num_posts; $i++){
if( in_array( $posts[$i]->ID, $sticky_posts ) ){
$sticky_post = $posts[$i];
//remove sticky post from current position
array_splice( $posts, $i, 1 );
//move to front, after other stickies
array_splice( $posts, $sticky_offset, 0, array( $sticky_post ) );
//increment the sticky offset. the next sticky will be placed at this offset.
$sticky_offset++;
//remove post from sticky posts array
$offset = array_search( $sticky_post->ID, $sticky_posts );
unset( $sticky_posts[$offset] );
}
}
}
return $posts;
}
add_filter('the_posts', 'putStickyOnTop' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment