Skip to content

Instantly share code, notes, and snippets.

@tdmrhn
Created August 20, 2024 21:31
Show Gist options
  • Save tdmrhn/0eed0953511d4079c5606b610cb3cc22 to your computer and use it in GitHub Desktop.
Save tdmrhn/0eed0953511d4079c5606b610cb3cc22 to your computer and use it in GitHub Desktop.
WP Show Sticky Posts First In Category Query
<?php
add_action('pre_get_posts', function($query) {
if ($query->is_main_query() && !is_admin() && $query->is_category()) {
$sticky_posts = get_option('sticky_posts');
if ($sticky_posts) {
$cat_id = get_queried_object_id();
$sticky_query = new WP_Query([
'post__in' => $sticky_posts,
'cat' => $cat_id,
'posts_per_page' => -1,
'ignore_sticky_posts' => 1
]);
$query->set('post__not_in', $sticky_posts);
$query->set('orderby', 'date');
add_filter('the_posts', function($posts) use ($sticky_query) {
return array_merge($sticky_query->posts, $posts);
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment