admin管理员组

文章数量:1303428

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

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

Share Improve this question asked Feb 9, 2021 at 14:49 davnshidavnshi 32 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 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;
?>

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

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

本文标签: How can I show only 5 posts from the relationship