Return posts with specific meta key first, but the rest in alpha order by last name

This may not be the best method, but I was able to achieve my desired result. I ended up setting up a second query.

functions.php

// List staff member by last name
function posts_orderby_lastname ($orderby_statement) {  

    $orderby_statement = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) ASC";

    return $orderby_statement;
}

staff-grid.php

    echo '<table>';
    echo '<tr>';

    // Query for Directors
    $meta_query = (array(
        'post_type' => 'staff',
        'staff-category' => $the_categories,
        'meta_query'     => array(
            array(
                'key'      => 'director',
                'value'    => 'yes',
                'compare'  => '!='
            ),
        ),
        'orderby'        => 'meta_value',
        'order'          => 'DESC'
    ));
    $meta = new WP_Query( $meta_query );

    // Begin iteration
    $i = 0;  

    if($meta->have_posts()) :

        while($meta->have_posts()) : $meta->the_post();

            $table_cell="<td>$posts</td>";

            echo $table_cell;

            $i++; 

            if($i % 2 == 0) { echo '</tr>'; }

        endwhile; $meta->reset_postdata();

    endif;


    add_filter( 'posts_orderby' , 'posts_orderby_lastname', 10, 2 );
    //Query all staff posts that are not directors
    query_posts (array(
        'post_type' => 'staff',
        'staff-category' => $the_categories,
        'meta_query'     => array(
            array(
                'key'      => 'director',
                'compare'  => 'NOT EXISTS'
            ),

        ),
    ));
    if(have_posts()) :

        while(have_posts()) : 
            the_post();

            $table_cell="<td>$posts</td>";

            echo $table_cell;

            $i++; 

            if($i % 2 == 0) { echo '</tr>'; }

        endwhile; 
        remove_filter( 'posts_orderby' , 'posts_orderby_lastname' );


        $i++; 

        if($i % 2 == 0) { echo '</tr>'; }

    endif;

    echo '</table>';

    wp_reset_query(); //Final reset just in case anything was missed

Leave a Comment