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?

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  ?>
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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