0

I have code for custom post type, for custom taxonomy for displaying category posts. I am using Advanced Custom Fields

What I want is to order posts by custom field value, and I was wondering how I can do it?

For example if posts have custom field called “rating” how can I order posts from lowest value to highest?

Here's an example code

<?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'brendovi' ) ); ?>
            <?php if (have_posts()): query_posts($query_string.'&posts_per_page=-1&orderby=date&order=ASC');  ?>
            <?php while( have_posts() ) : the_post(); ?>

This is the code that works just fine for displaying most recent custom post type posts, and they have custom fields called field_1, field_2, field_3. And users will fill those fields with numeric value. And later on on single post, I'll do the calculation summing those values and dividing by 3 to get avg value. Let's call it field_4.

I am stuck at displaying posts and sorting them by that field_4 with query string.

Perhaps I don't need query string?

5
  • Please share your code, what you have tried and what doesn't work. Commented Dec 1, 2017 at 19:19
  • WP_Query Orderby Parameters Commented Dec 2, 2017 at 9:23
  • I've added the code Commented Dec 2, 2017 at 10:10
  • Don't use query_posts(). Use the pre_get_posts hook. Commented Dec 2, 2017 at 10:22
  • @Jacob cab you provide me with sample code for my case? Commented Dec 2, 2017 at 16:42

1 Answer 1

0

The query_posts is only useful when you actually know what you are doing. Base on the info you provide this should work for you :

$the_query = new WP_Query(array(
    'post_type'         => 'your_cpt',
    'posts_per_page'    => -1,//get them all
    'meta_key'          => 'field_4',
    'orderby'           => 'meta_value',
    'order'             => 'DESC'
));

?>
<?php if( $the_query->have_posts() ): ?>
    <ul>
    <?php while( $the_query->have_posts() ) : $the_query->the_post(); 

        $class = get_field('field_4');

        ?>
        <li <?php echo $class; ?>>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
    <?php endwhile; ?>
    </ul>
<?php endif; ?>

<?php wp_reset_query();  // Restore global post data  ?>

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.