Sort posts based on multiple custom fields

I have a three custom fields

  • Meta Key → YOUR_PREFIX_newcar_body_type
  • Meta Key → YOUR_PREFIX_newcar_transmission_type
  • Meta Key → YOUR_PREFIX_newcar_variant

and I have to sort posts based on these custom fields and print the title of the post…

Read More

Any ideas?

Related posts

Leave a Reply

1 comment

  1. Unfortunately, I don’t believe WordPress has the ability to sort by multiple meta key criteria as part of the query: only one. This is likely because for each meta key value selected, another JOIN is involved. You can also see that there are no hooks to modify the ORDER BY clause in SQL in the WP_Query class. This can be seen in wp-includes/query.php line 2322

    That said, it is certainly possible to do the ordering in PHP.

    $posts = get_posts( $query );
    
    function prefix_sort_by_meta( $a, $b ) {
       $custom_a = get_post_custom( $a->ID );
       $custom_b = get_post_custom( $b->ID );
       return strcmp(
            $custom_a['YOUR_PREFIX_newcar_body_type'][0] . '-' . $custom_a['YOUR_PREFIX_newcar_transmission_type'][0] . '-' . $custom_a['YOUR_PREFIX_newcar_variant'][0],
            $custom_b['YOUR_PREFIX_newcar_body_type'][0] . '-' . $custom_b['YOUR_PREFIX_newcar_transmission_type'][0] . '-' . $custom_b['YOUR_PREFIX_newcar_variant'][0]);
    }
    usort( $posts, 'prefix_sort_by_meta' );
    global $post;
    // Pseudo-loop
    foreach( $posts as $post ) {
       setup_postdata( $post );
    
       // Your item template here...
    }
    

    This is just one way to achieve ordering by meta key values: join the meta key values with ‘-‘ and sort as a string. You can play with the prefix_sort_by_meta function to achieve different sorting methods. Please note that the above code will throw PHP Notices if the various meta keys don’t exist for any of the posts, and should be coded more defensively.