Show Featured Items First on Post Type Archives
Adds a "Featured" checkbox to chosen post types and lists featured items at the top of their archives, newest first after that.
Opens WPIDE on
Code
// Post types that get the Featured checkbox and ordering.
$wpide_featured_types = array( 'event', 'job', 'property' );
add_action( 'add_meta_boxes', function ( $post_type ) use ( $wpide_featured_types ) {
if ( ! in_array( $post_type, $wpide_featured_types, true ) ) {
return;
}
add_meta_box( 'wpide-featured', 'Featured', function ( $post ) {
wp_nonce_field( 'wpide_featured_save', 'wpide_featured_nonce' );
printf( '<label><input type="checkbox" name="wpide_featured" value="1"%s> Show at the top of the archive</label>', checked( get_post_meta( $post->ID, '_wpide_featured', true ), '1', false ) );
}, $post_type, 'side', 'high' );
} );
add_action( 'save_post', function ( $post_id, $post ) use ( $wpide_featured_types ) {
if ( ! in_array( $post->post_type, $wpide_featured_types, true ) || ! isset( $_POST['wpide_featured_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wpide_featured_nonce'] ), 'wpide_featured_save' ) ) {
return;
}
if ( wp_is_post_autosave( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( ! empty( $_POST['wpide_featured'] ) ) {
update_post_meta( $post_id, '_wpide_featured', '1' );
} else {
delete_post_meta( $post_id, '_wpide_featured' );
}
}, 10, 2 );
add_filter( 'posts_clauses', function ( $clauses, $query ) use ( $wpide_featured_types ) {
global $wpdb;
if ( is_admin() || ! $query->is_main_query() || ! $query->is_post_type_archive( $wpide_featured_types ) ) {
return $clauses;
}
// Join the flag once and sort flagged items first, keeping the existing order after that.
$clauses['join'] .= $wpdb->prepare( " LEFT JOIN {$wpdb->postmeta} AS wpide_feat ON ( wpide_feat.post_id = {$wpdb->posts}.ID AND wpide_feat.meta_key = %s )", '_wpide_featured' );
$clauses['orderby'] = "( wpide_feat.meta_value = '1' ) DESC" . ( $clauses['orderby'] ? ', ' . $clauses['orderby'] : '' );
return $clauses;
}, 10, 2 );
Notes
Change the post types in $wpide_featured_types. Sticky posts already do this for the blog.
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.