0

I'm making the following query in order to get all the posts sorted by a meta key (wpcf-estado in this case) but it returns the items in no order:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = array( 
                        'post_type' => 'proyectos',
                        'posts_per_page' => 8,
                        'paged' => $paged,
                        'orderby' => 'meta_value',
                        'order' => 'DESC',
                        'meta_key' => 'wpcf-estado',
                        //'meta_value' => 'a',                                      
        );

If I uncomment the 'meta_value' parameter, I end up succesfully getting only the posts containing 'a' as wpcf-estado.

The possible values of wpcf-estado are: a, b or c.

I tried several things but didn't find a proper solution.

4
  • Your first line implies you're using query_posts or a replacement WP_Query, consider using a pre_get_posts filter instead, it should make the page ~2x as fast, and allow you to remove all the pagination fixing code
    – Tom J Nowell
    Sep 13, 2016 at 22:19
  • Also, if you're trying to categorise by type A B or C, a taxonomy with terms A B and C would be more performant than post meta
    – Tom J Nowell
    Sep 13, 2016 at 22:20
  • Can you try adding 'meta_type' => 'char'?
    – Tom J Nowell
    Sep 13, 2016 at 22:21
  • Tried with no success.
    – Rod0n
    Sep 13, 2016 at 22:39

2 Answers 2

1

@Rod0n WP version 4.2 included the number of improvements in WP_QUERY particularly when use the 'meta_query' parameter. Also, check the WP_QUERY Class Refernece.


$args = array( 
         'post_type' => 'proyectos' ,
         'posts_per_page' => 8 , 
         'paged' => $paged,
         'orderby' => array(
           'meta_value' => 'DESC'
          ), 
         'meta_query' => array(
           array(
             'key' => 'wpcf-estado',
             'compare' => 'EXISTS',
          ),
       ),
    );

Hope it will work for you!

1

Did you tried with 'orderby' => 'meta_value_num' ?

Even better I think and shothand

$args = array( 
    'post_type' => 'proyectos',
    'posts_per_page' => 8,
    'paged' => $paged,
    'orderby'  => array( 'meta_value_num' => 'DESC', 'title' => 'ASC' ),
    'meta_key' => 'wpcf-estado'
    //'meta_value' => 'a',                                      
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.