Primary and Secondary Sorting in WordPress

I am creating a WordPress theme that catalogs albums, and I have created the custom post type, created the custom fields, and have them successfully pulling in. I have several custom fields including; Artist, Album, Size, Label etc. I currently have the posts sorting alphabetically by the Artist name with this array:

$args=array(
‘post_type’ => ‘albums’,
‘order’ => ‘ASC’,
‘meta_key’ => ‘custom_meta_artist’,
‘orderby’ => ‘meta_value’,
‘posts_per_page’ => -1,
);

Read More

But I would also like the Albums, ‘custom_meta_album’, to sort alphabetically if it is the same Artist. Currently if a user enters in 10 albums by the same artist, the post will be alphabetized correctly by the Artist name, but the Albums have no order.

Is there a way to do some sort of second level sorting or primary and secondary sorting in WordPress? I don’t know if it’s a IF statement that says “if artists value is equal then also sort albums ascending” or something along those lines. I figure there needs to be some way to tell WordPress which field it should sort by first and then continue to the second level.

Related posts

Leave a Reply

1 comment

  1. You may try this, hope this will work

    // keep this function in your functions.php
    function myCustomOrderby($orderby) {
        return str_replace('menu_order', 'mt1.meta_value, mt2.meta_value', $orderby);
    }
    

    This is your args array

    $args=array(
        'post_type' => 'albums',
        'orderby' => 'title',
        'order' => 'ASC',
        'posts_per_page' => -1,
        'meta_query' => array(
             array(
                'key' => 'custom_meta_artist',
                'value' => '',
                'compare' => 'LIKE'
            ),
            array(
                'key' => 'custom_meta_album',
                'value' => '',
                'compare' => 'LIKE'
            )
        )
    );
    add_filter('posts_orderby','myCustomOrderby'); // Add filter before you call the WP_Query
    $albums = new WP_Query($args);
    remove_filter('posts_orderby','myCustomOrderby'); // Remove filter after you call the WP_Query
    // Start your loop
    while ( $albums->have_posts() ) : $albums->the_post();
        //...
    endwhile;