Forums

wp_query ordered by custom field value (4 posts)

  1. Alejandro Urrutia
    Member
    Posted 1 year ago #

    Hi everyone, I am using in my portfolio the following wp_query:

    <?php $loop = new WP_Query( array( 'post_type' => 'work', 'posts_per_page' => 999, 'order' => DESC ) ); while ( $loop->have_posts() ) : $loop->the_post(); ?>
    
    .....

    And it's working perfectly, what I want is to order by "Year" Custom Field Value, of course is a numeric value such as: 2001, 2007 or 2010.

    How can I do it?

    Thanks in advance!
    Best regards.

  2. jamespiggot
    Member
    Posted 1 year ago #

    Have you tried using orderby=meta_value together with metakey=year

    This will be a alpha rather than numeric sort but with your data values of just year it should work correctly.

    There is some documentation for this in the Codex under query_posts which explains somewhat what is required.

  3. Alejandro Urrutia
    Member
    Posted 1 year ago #

    Hi James,

    Thanks for replying and for enlighten the way to find the solution.
    Here's the resulting code for anyone who wants to use it:

    <?php $loop = new WP_Query( array( 'post_type' => 'work', 'posts_per_page' => 999, 'meta_key'=>'year',  'orderby' => 'meta_value_num', 'order' => DESC ) ); while ( $loop->have_posts() ) : $loop->the_post(); ?>
    ...

    Regards.

  4. ixwa
    Member
    Posted 10 months ago #

    Hmm, meta_value_num didn't work for me but meta_value did. Just be sure that orderby is on the same level as post_type etc.

Topic Closed

This topic has been closed to new replies.

About this Topic