Home › Forums › General Issues › Order of Posts Using Relationship Field
I am having troubles wrapping my brain around this. Perhaps it is easy and I am just overthinking this.
I am using the relationship field to show a list from a custom post type called ‘speaker_info’ on a page. Each of these ‘speaker_info’ post entries has an advance custom field entry for ‘last_name’ and ‘first_name.’
I need to be able to show this list ordered by the custom field ‘last_name’
Currently I just have the default code from the example page, and have tried different queries with no luck.
<?php
$posts = get_field('speakers_two');
if( $posts ): ?>
<ul>
<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
<?php setup_postdata($post); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<span>Custom field: <?php the_field('last_name'); ?></span>
</li>
<?php endforeach; ?>
</ul>
<?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?>
Can anyone please help me change this so that I may query the custom post types by the last_name custom field.
Have you tried it using a WP_Query? Like this for instance:
<?php
$speakers = get_field('speakers_two');
$query = new WP_Query(array(
'post_type' => 'speaker_info',
'post__in' => $speakers,
'meta_key' => 'last_name',
'orderby' => 'meta_value',
'order' => 'ASC',
));
if ($query->have_posts()) : ?>
<ul>
<?php while($query->have_posts()) :
$query->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<span>Custom field: <?php the_field('last_name'); ?></span>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
Let me know if it works or not, it did the trick for me with a relationship field I wanted to sort.
Thanks for that! I did end up using something quite similar.
The topic ‘Order of Posts Using Relationship Field’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.