Home › Forums › General Issues › Order posts by date using relationship field
Hi there!
I’m looking for help… my problem is simple to explain. I need to display posts linked to a page or a Custom Post Type using the relationship field.
It works fine doing this:
<?php $posts = get_field('my_custom_field'); if( $posts ): ?>
<ul>
<?php foreach( $posts as $post): ?>
<?php setup_postdata($post); ?>
<li class="line">
<a title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt(); ?>
</li>
<?php endforeach; ?>
</ul>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
But, I need to display them by post_date. I tried to do using get_posts but I don’t really what do with the meta_query…
Here is what I did:
<?php
$posts = get_posts(array(
'post_type' => 'post',
'orderby' => 'post_date',
'meta_query' => array(
array(
'key' => 'my_custom_field', // name of custom field
'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
)
)
));
if( $posts ) {
?>
<a title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt(); ?>
<?php } ?>
Thanks!
Hi @Aurelien Denis
The easiest way to achieve this is to use the ‘post__in’ arg like so:
<?php
$post_ids = get_field('my_custom_field', false, false);
$posts = get_posts(array(
'post_type' => 'post',
'orderby' => 'post_date',
'post__in' => $post_ids,
));
if( $posts ) {
?>
<a title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt(); ?>
<?php } ?>
note the 2 false parameters in the get_field function? This will tell ACF not to format the value, so you will get an array of ID’s, not an array of post objects!
Yep it seems to works. Here is it what I did based on your solution:
<?php
$post_ids = get_field(' my_custom_field', false, false);
$posts = get_posts(array(
'post_type' => 'post',
'orderby' => 'post_date',
'posts_per_page' => -1,
'post__in' => $post_ids,
));
if( $posts ) {
?>
<ul>
<?php foreach( $posts as $post): ?>
<?php setup_postdata($post); ?>
<li class="line">
<a title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt(); ?>
</li>
<?php endforeach; ?>
</ul>
<?php } ?>
Any advice are welcome. 😉
The topic ‘Order posts by date 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.