Home > other >  Wordpress - display posts by custom field and order by another
Wordpress - display posts by custom field and order by another

Time:12-31

I have custom WP_Query call where I need to display CPT property by one custom field floor with meta_value second_floor and sort them by another field apartment_number with 'orderby' => 'meta_value'. Whole code:

   $args = array(
        'post_type' => 'property',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'order' => 'ASC',
        'meta_key' => 'floor',
        'meta_value' => 'second_floor',
        'meta_compare' => 'LIKE',
        'meta_key' => 'apartment_number',
        'orderby' => 'meta_value',

    );
    
    $query = new WP_Query( $args );

CodePudding user response:

Your query can be performed by using the meta_query as explained here https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters

With the meta query, you've included a value, then using the orderby clause in the main query, you can specify that you want to order by a meta_value as explained here https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters

$args = array(
    'post_type'      => 'property',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => array(
        array(
            'key'     => 'floor',
            'value'   => 'second_floor',
            'compare' => 'LIKE',

        ),
    ),
    'order'          => 'ASC',
    'meta_key'       => 'apartment_number',
    'orderby'        => 'meta_value',

);

To clarify, this is the resulting SQL from the above WP_Query:

SELECT wp_posts.*
FROM wp_posts
         INNER JOIN wp_postmeta
                    ON ( wp_posts.ID = wp_postmeta.post_id )
         INNER JOIN wp_postmeta AS mt1
                    ON ( wp_posts.ID = mt1.post_id )
WHERE 1=1
  AND ( wp_postmeta.meta_key = 'apartment_number'
    AND ( ( mt1.meta_key = 'floor'
        AND mt1.meta_value LIKE '%second\\_floor%' ) ) )
  AND wp_posts.post_type = 'product'
  AND ((wp_posts.post_status = 'publish'))
GROUP BY wp_posts.ID
ORDER BY wp_postmeta.meta_value ASC
  • Related