Query by meta_key and order by meta_value_num return orderby date

I’m trying to use the orderby and custom WP_Query features of wordpress.
It works nicely to select item by their meta and to order by date.

Unfortunately, it seems that I could not get the post result ordered by a meta_value numeric.

Read More

Here is the args for the query :

$args = array(
                'post_status' => 'publish',
                'post_type' => 'participant',
                'order' => 'DESC',
                'meta_key' => 'participant_partage_class',
                'order_by' => 'meta_value_num,
                'meta_query' => array(
                             'key' => 'participant_partage_class',
                             'type' => 'SIGNED',
                             'compare' => '>',
                        ),
                'posts_per_page' => '8',
                'paged' => $paged
            );

This result in the following query (token via request $GLOBALS['wp_query']->request) :

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) WHERE 1=1 AND wp_posts.post_type = 'participant' AND (wp_posts.post_status = 'publish') AND (wp_postmeta.meta_key = 'participant_partage_class' ) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 8, 8

Which can not gave the list in order by meta_value.

What I’ve seen is that this query :

SELECT wp_posts.*
FROM wp_posts 
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
WHERE 1=1
  AND wp_posts.post_type = 'participant'
  AND (wp_posts.post_status = 'publish')
  AND wp_postmeta.meta_key = 'participant_partage_class'
GROUP BY wp_posts.ID
ORDER BY CAST(wp_postmeta.meta_value AS SIGNED) DESC
LIMIT 0, 8;

So my question is, how to handle this by simply using WP_Query object and not the default MySQL approach?

Related posts

1 comment

  1. The problem in your code is ‘meta_query’ code is write insde array of array

    $args = array(
                    'post_status' => 'publish',
                    'post_type' => 'participant',
                    'order' => 'DESC',
                    'meta_key' => 'participant_partage_class',
                    'orderby' => 'meta_value_num,
                    'meta_query' => array(array(
                                 'key' => 'participant_partage_class',
                                 'type' => 'SIGNED',
                                 'compare' => '>',
                            )),
                    'posts_per_page' => '8',
                    'paged' => $paged
                );
    $query = new WP_Query($args);
    

    http://codex.wordpress.org/Class_Reference/WP_Query

    you can check here how to use ‘meta_query’ in wp_query

Comments are closed.