How can I show only 5 posts from the relationship?

HI
I use plugin: Advanced Custom Fields

How can I show only 5 posts from the relationship?

This is the code:

<?php $c_lists = get_field( 'c_lists' ); ?>
<?php if ( $c_lists ) : ?>
    <?php foreach ( $c_lists as $post_ids ) : ?>
        <a href="<?php echo get_permalink( $post_ids ); ?>"><?php echo get_the_title( $post_ids ); ?></a>
    <?php endforeach; ?>
<?php endif; ?>

Any help, please

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could use the key from the foreach

<?php
$c_lists = get_field('c_lists');
if ($c_lists) :
    foreach ($c_lists as $key => $post_ids) :
    if ($key > 4) break;
?>
<a href="<?= get_permalink($post_ids); ?>"><?= get_the_title($post_ids); ?></a>
<?php
    endforeach;
endif;
?>

Method 2

You can follow such a path

<?php if ( $c_lists ) : ?>
    <?php $max = 5; $start = 0; foreach ( $c_lists as $post_ids ) : 
    $start++; 
    if( $start >= $max ) break;
    ?>
        <a href="<?php echo get_permalink( $post_ids ); ?>"><?php echo get_the_title( $post_ids ); ?></a>
    <?php endforeach; ?>
<?php endif; ?>

Method 3

Yet another option: you can array_slice the array you pass into the foreach

<?php $c_lists = get_field( 'c_lists' ); ?>
<?php if ( $c_lists ) : ?>
    <?php foreach ( $c_lists as array_slice( $post_ids, 0, 5 ) ) : ?>
        <a href="<?php echo get_permalink( $post_ids ); ?>"><?php echo get_the_title( $post_ids ); ?></a>
    <?php endforeach; ?>
<?php endif; ?>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x