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.