How to use custom fields to enable sticky posts on custom post types?

Background: The WordPress Answers site has two questions which ask about how to enable sticky posts on custom post types (see how to make custom posts sticky? and Enable sticky posts to custom post_type ). Both questions made mention of this trac ticket ( https://core.trac.wordpress.org/ticket/12702 ).

The answers provided ( to those questions I mentioned above ) express a possibility of using custom post types and meta-boxes. Unfortunately the level of detail in those answers was not helpful to me (and, I presently don’t have enough reputation to comment for further clarification).

My Goal: I am using the custom post type ui plugin and the advanced custom fields plugin to display employee profile CPT’s. One one of my pages lists all of the employee profiles, but the client wants certain profiles to be stick to the top. I have reviewed two possible plugins to assist me (seamless sticky custom post types and sticky custom post types). Unfortunately, those plugins seem only to output the sticky post on the homepage.

For my purposes, the sticky-feature should only apply to the specialized page template that lists all the employee profiles, and not the home page.

Question Restatement: It seems like the best solution for me involves somehow using custom fields to accomplish the desired result. Is this correct? If so, please direct me to any wordpress template tags, techniques, examples or tutorials that might help.

1 Answer
1

You can achieve this with ACF.

Create a custom field checkbox (just a simple boolean) for your custom post type.
Below an example of overriding the main loop in archive template :

function order_cpt_by_stickyness( $query ) {
    if(!is_admin() && $query->is_main_query() && is_post_type_archive('my_custom_postype')) {
        $query->set( 'meta_key', 'my_sticky_custom_field');
        $query->set( 'orderby', ['meta_value' => 'DESC', 'date' => 'DESC']);
    }
}
add_filter( 'pre_get_posts', 'order_cpt_by_stickyness' );

Leave a Comment