Implementing Sticky Categories in WordPress

Sticky posts are a very useful feature in WordPress, allowing us to pin certain important articles to the top of the homepage or category list. But can we “sticky” categories as well? In some scenarios, such as when the website has many categories but we want to display some prioritized ones on the mobile home page, sticky categories are very useful.

There are many ways to implement sticky categories, like adding a custom field for categories or simply using category IDs. This article shows a simple and flexible implementation using the WordPress Hook system and Options API.

Adding Sticky Checkbox to Category Edit Page

First, we need to add a “Sticky” checkbox to the category editing page. We achieve this by hooking into category_edit_form_fields. The code is as follows:

add_action('category_edit_form_fields', function ($tag)
{
    $featured_term = get_option('featured_term');
    $checked = (is_array($featured_term) && in_array($tag->term_id, $featured_term)) ? 'checked' : '';
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="featured-term">Sticky Category</label></th>
        <td>
            <input type="checkbox" name="featured_term" id="featured-term" value="1" <?php echo $checked; ?>>
            <p class="description">Check to pin this category.</p>
        </td>
    </tr>
    <?php
});

After adding the code, you will see a “Sticky Category” option on the category editing page, as shown in the screenshot below:

Fetching Sticky Categories

Now that we have the sticky category information, retrieving them is very simple. You can call them using the code below. If you need to exclude sticky categories, replace include with exclude.

$featured_terms = get_option('featured_term');
$terms = get_terms( [
        'taxonomy' => 'category',
        'include'  => $featured_terms,
] );

Not only for categories, but tags and custom taxonomies can also have sticky functionality implemented in a similar way; you just need to save the data in appropriate settings. The WordPress Hook system is a very flexible and powerful feature. Properly utilized, we can add various features to WordPress to meet our needs.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *