Home / Archive / Sticky Posts on Category Pages
Duplicate Snippet

Embed Snippet on Your Site

Sticky Posts on Category Pages

Make sticky posts show up first on category archive pages, not just the homepage.

<10
Code Preview
php
<?php
add_action('pre_get_posts', function($query) {
    if (!is_admin() && $query->is_main_query() && is_category()) {
        $sticky_posts = get_option('sticky_posts');
        if (!empty($sticky_posts)) {
            add_filter('posts_orderby', function($orderby, $query) use ($sticky_posts) {
                if (!is_admin() && $query->is_main_query() && is_category()) {
                    global $wpdb;
                    $sticky_list = implode(',', array_map('intval', $sticky_posts));
                    return "FIELD({$wpdb->posts}.ID, {$sticky_list}) DESC, {$orderby}";
                }
                return $orderby;
            }, 10, 2);
        }
    }
});

Comments

Add a Comment