Use CMB2 to create a yes/no select field and query posts by that value
<?php
//* Do NOT include the opening php tag shown above. Copy the code shown below.
add_action( 'cmb2_admin_init', 'pb_cmb2_service_featured' );
function pb_cmb2_service_featured() {
$prefix = '_pb_service_featured_';
$cmb_service_featured = new_cmb2_box( array(
'id' => 'test_metabox',
'title' => __( 'Make Service Featured', 'cmb2' ),
'object_types' => array( 'pb_cpt_services', ), // Post type
'context' => 'side',
'priority' => 'low',
'show_names' => true, // Show field names on the left
// 'cmb_styles' => false, // false to disable the CMB stylesheet
// 'closed' => true, // Keep the metabox closed by default
) );
// Regular text field
$cmb_service_featured->add_field( array(
// 'name' => __( 'Make Service Featured', 'cmb2' ),
'desc' => __( 'Set to yes to move this service to the top of the services page. Set only one service as featured at a time.', 'cmb2' ),
'id' => $prefix . 'select_featured',
'type' => 'select',
'show_option_none' => false,
'default' => 'No',
'options' => array(
'no' => __( 'No', 'cmb2' ),
'yes' => __( 'Yes', 'cmb2' ),
),
'column' => array(
'position' => 2,
'name' => 'Featured',
),
) );
}
<?php
//* Do NOT include the opening php tag shown above. Copy the code shown below.
add_action( 'pre_get_posts', 'pb_change_services_query' );
function pb_change_services_query( $query ) {
if( $query->is_main_query() && !is_admin() && is_post_type_archive( 'pb_cpt_services' ) ) {
$meta_query = array (
array(
'key' => '_pb_service_featured_select_featured',
'value' => 'yes',
'compare' => '=',
)
);
$query->set( 'meta_query', $meta_query );
$query->set( 'orderby', 'meta_value' );
$query->set( 'meta_key', '_pb_service_featured_select_featured' );
$query->set( 'order', 'DESC' );
$query->set( 'posts_per_page', '1' );
}
}