Sticky Posts First in Category Archives
Puts sticky posts at the top of the category archives they belong to, the same way WordPress already does on the blog page.
Opens WPIDE on
Code
add_filter( 'the_posts', function ( $posts, $query ) {
if ( is_admin() || ! $query->is_main_query() || ! $query->is_category() || $query->is_paged() ) {
return $posts;
}
$sticky = array_map( 'absint', (array) get_option( 'sticky_posts', array() ) );
if ( ! $sticky ) {
return $posts;
}
$pinned = get_posts( array(
'post__in' => $sticky,
'category__in' => array( $query->get_queried_object_id() ),
'numberposts' => count( $sticky ),
'ignore_sticky_posts' => true,
'no_found_rows' => true,
) );
if ( ! $pinned ) {
return $posts;
}
$pinned_ids = wp_list_pluck( $pinned, 'ID' );
$others = array_filter( $posts, function ( $post ) use ( $pinned_ids ) {
return ! in_array( $post->ID, $pinned_ids, true );
} );
return array_merge( $pinned, array_values( $others ) );
}, 10, 2 );
Notes
Only the first page of each category archive is affected.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.