0

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

3 Answers 3

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;
?>
1
  • This works fine thanks bro
    – davnshi
    Feb 9, 2021 at 15:09
0

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; ?>
1
  • That works too, thanks bro
    – davnshi
    Feb 9, 2021 at 16:26
0

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; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.