orderby CMB2 field

By setting a meta_key to the field you want to sort after you can modify the order of a query based on a cmb2 field and also combine with others.
This example sort by the field first then after date

        $query->set('meta_key', '_mycmb2box_myspecialfield' );
        $query->set('orderby', array('meta_value' => 'DESC', 'date' => 'DESC'));

This example pre gets ALL posts for a CPT and then sorting based on cmb2 values:

add_action( 'pre_get_posts', 'my_custom_namespace_pre_get_post' );
function my_custom_namespace_pre_get_post( $query ) {
    if( is_post_type_archive( 'my_custom_namespace_my_custom_post_type' ) && !is_admin() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', -1 );
        $query->set('meta_key', '_my_custom_namespace_my_custom_field' );
        $query->set('orderby', array('meta_value' => 'DESC', 'date' => 'DESC'));

Important to note that if the meta key is not set for a post it won’t load in at all, so use that with a cmb2 field
its good to set a default value in the following manner:

    $my_custom_namespace->add_field( array(
        'name'        => __( 'Custom Field', 'my_custom_namespace' ),
        'desc'       => __( 'This is my custom field', 'my_custom_namespace' ),
        'id'         => $prefix . 'my_custom_field',
        'type'       => 'text',
        'default' => '0',
        'attributes' => array(
            'type' => 'number',
    ) );

Add your comment