Support

Account

Home Forums ACF PRO Orderby custom field not working

Solving

Orderby custom field not working

  • Hi

    I’m sure I am doing something wrong here but I cannot get a wp_query to order results by a custom field (number type). Very basically I have a custom post type called ‘holidays’ which has a custom field called ‘price_from’ and I just want to loop through the posts in descending order by default. My code is:

    
    $args = array(
         'post_type'     => 'holidays',
         'numberposts'   => -1,
         'meta_key'      => 'price_from',
         'orderby'       => 'meta_value',
         'order'         => 'DESC'
    );
    // query
    $the_query = new WP_Query( $args );
    

    And I am testing this query like so:

    
    <?php if( $the_query->have_posts() ): ?>
    <ul>
        <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <li><?php the_field('price_from'); ?></li>    
        <?php endwhile; ?>
    </ul>
    <?php endif; ?>
    

    But it gives me a result like this:

    999
    1999
    1729
    1729
    1695
    1499
    14595
    1299

    It seems to put the last result first and then only order by the first two numbers. It’s driving me nuts for such a simple query, can anyone point out my probably obvious mistake?

    Thanks

  • Fixed :). In case anyone else has the same problem it was because:

    'orderby' => 'meta_value'

    Should have been:

    'orderby' => 'meta_value_num'

  • Very useful, it was driving me nuts and fortunately this post appeared in my search engine results.

    Had no idea that it needed to be 'orderby' => 'meta_value_num'

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Orderby custom field not working’ is closed to new replies.