How can I show only 5 posts from the relationship?
-
22-04-2021 - |
Frage
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
Lösung
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;
?>
Andere Tipps
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; ?>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit wordpress.stackexchange