Order Wp query based on a custom field value

I have written a wp query to list custompost types (motobikes) based on 2 keys. (brand which is variable and type)
The query works and lists my customposts properly, but I would like to order them based on a 3 key value which is the cylinder (‘key => cylindree’)
I did not find a way to order by a specific custom field value that is not in the query.
Here is my query so far :

$args = array(
    'post_type' => 'motos',
    'posts_per_page'=> -1,
    'meta_query' => array(
        array( 
            'key' => 'categorie',
            'value' => 'Roadster'
        ),
        array( 
            'key' => 'marque',
            'value' => $meta_value 
        )
    )
);

[…]

Read More

Thank you for your help.

Best regards.

Related posts

2 comments

  1. You can add a meta_key to order by:

    $args = array(
        'post_type' => 'motos',
        'posts_per_page'=> -1,
        'meta_key' => 'cylindree',
        'orderby' => 'meta_value',
        'meta_query' => array(
            array( 
                'key' => 'categorie',
                'value' => 'Roadster'
            ),
            array( 
                'key' => 'marque',
                'value' => $meta_value 
            )
        )
    );
    
  2. Try this, it works for me:

    global $wpdb;
    
    $query = "
        SELECT  
            wp_posts.ID, pm1.meta_value AS your_custom_field
        FROM 
            wp_posts
        LEFT JOIN
            wp_postmeta AS pm1 ON (wp_posts.ID = pm1.post_id AND pm1.meta_key = 'name_of_custom_field_in_database')
        WHERE 
            wp_posts.post_type = 'your_post_type' AND 
            wp_posts.post_status = 'publish'
        ORDER BY your_custom_field
    ";
    
    $posts = $wpdb->get_results($query);
    

Comments are closed.