Reputation: 1399
I need to order the following wordpress loop by a custom field. Where can i set the order in this loop?
<?php
if ( $query->have_posts() ) { ?>
<?php
while ($query->have_posts())
{
$query->the_post();
?>
// THE CONTENT
<?php } ?>
Upvotes: 1
Views: 7904
Reputation: 2708
You can customize the order by passing args on WP_Query
. For meta
$args = array(
'post_type' => 'my_custom_post_type',
'meta_key' => 'age',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'age',
'value' => array( 3, 4 ),
'compare' => 'IN',
),
),
);
$query = new WP_Query( $args );
See here for more details.
Upvotes: 0
Reputation: 2702
This example will use the get_posts function to load all the ‘events’ posts ordered by a custom field value of ‘start_date’.
<?php
// get posts
$posts = get_posts(array(
'post_type' => 'event',
'posts_per_page' => -1,
'meta_key' => 'start_date',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));
if( $posts ): ?>
<ul>
<?php foreach( $posts as $post ):
setup_postdata( $post )
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?> (date: <?php the_field('start_date'); ?>)</a>
</li>
<?php endforeach; ?>
</ul>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
refer https://www.advancedcustomfields.com/resources/orde-posts-by-custom-fields/
Upvotes: 1