Support

Account

Home Forums General Issues Orderby Custom Field does not work

Helping

Orderby Custom Field does not work

  • Hi

    I got a little problem. I have a page for our Team and added a custom Field with acf to add an id that i can use to sort the members in a list. The field works as i can display it in the post_type “team” but the sorting does not work as expected.

    As a recsource for the code i used: https://www.advancedcustomfields.com/resources/order-posts-by-custom-fields/

    The Posts still get sorted by publishing date.

    
    <?php
        $the_query = new WP_Query(array( 
            "post_type" => "team", 
            "posts_per_page" => -1,
            "meta_key" => "team_id",
            "meta_type" => "numeric",
            "orderby" => "meta_key",
            "order" => "DESC",
            "post_status" => "publish"
        ));
    
        if ( $the_query -> have_posts() ) : ?>
                <div class="container">
                    <div class="row">
                        <?php if ( $the_query -> have_posts() ) : $i = 0;
                            while ( $the_query -> have_posts() ) : $the_query -> the_post(); $i ++;
                                    print $team_id;the_field("team_id");
                               if ( $i % 2 === 0 ) : ?>
                                    <div class="clearfix"></div>
                                <?php endif; ?>
                            <?php endwhile; ?>
                        <?php endif; ?>
                    </div>
                </div>
    

    output

    
    0 1
    2 3
    4 5
    6 7
    14 8
    9 10
    12 11
    13 
    

    As you can see the #14 is right in the middle of the list but should be at the end.

    And yes i know the code is not very nice but i am only adjusting a template that is a couple of years old.

    Any hint why it is not working is highly appreciated!

  •     <?php 
        $the_query = new WP_Query(array( 
            "post_type" => "team",
            "posts_per_page" => -1,
            "meta_key" => "team_id",
            "orderby" => "meta_value_num",
            "order" => "ASC",
            "post_status" => "publish"
        ));?>

    This does work as intended.

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

You must be logged in to reply to this topic.