WordPress Query: ORDER BY CASE WHEN

I want to first display the posts that match a particular meta_key => cr_id and order those by another 'meta_key' => 'cr_list_price' and then display the rests of the posts that are also ordered by 'meta_key' => 'cr_list_price'.

This is my current code which does everything I want except show the posts where cr_id = 4.

Read More
    $args = array(
        'post_type' => 'properties',
        'paged' => get_query_var( 'paged' ),
        'meta_query' => array(
            array(
                'key' => 'cr_list_price',
                'value' => array($minPrice, $maxPrice),
                'type' => 'numeric',
                'compare' => 'BETWEEN'
            ),
            array(
                'key' => 'cr_prop_bed',
                'value' => $beds,
                'compare' => '>='
            ),
        ),
        'orderby' => 'meta_value_num',
        'meta_key' => 'cr_list_price'
    );

    $loop = new WP_Query( $args );

If I was using raw MySQL I’d do something like ORDER BY CASE WHEN in my query, however I’m not sure how or if I can accomplish this with WordPress.

Related posts

Leave a Reply

1 comment

  1. I wonder if you could add a filter to the query by adding that little extension on there. I’m thinking maybe posts_orderby

    Function

    function filter_case($orderby = '') {
      $orderby .= 'CASE WHEN [some conditions]';
      return $orderby;
    }
    

    Before Query

    add_filter( 'posts_orderby', 'filter_case' );
    
    $wp_query = new WP_Query($args);
    
    remove_filter( 'posts_orderby', 'filter_case' );
    

    I cant gaurantee this will work first time but it could be worked on if you think it’s worth pursuing? List of WP_Query filters are here.