You're defining $storelink
inside the foreach ( $storelist as $post )
loop, but not using it until you've ended the loop, meaning only the last $storelink defined will be available. If you need to accumulate a bunch of store names and titles you might consider something like:
$stores = array();
foreach ( get_field( 'storelist' ) as $store ) {
$stores[] = array(
'name' => get_the_title( $store->ID ),
'link' => strip_tags( get_field( 'storelink', $store->ID ) )
);
}
Then you'll have an array of stores to purchase the book that you can use to build the links (if I'm understanding your usage correctly; either way, the mystery of $storelink
only being correct for the last item in the loop is because the variable is never used until after the loop).
Edit: Your updated version tries to reference specific array keys that don't exist; I'm afraid I may have confused things more with my array suggestion. If I understand correctly what you're trying to do, something like this should fit the bill:
<?php while ( have_posts() ) : the_post(); ?>
<div class="bookindex">
<?php
// Since $bookinfo and $bookcode don't appear to change, we'll get them once and save it
$bookinfo = get_field( 'bookinfo', $post->ID );
$bookcode = get_field( 'bookcode', $post->ID );
?>
<?php foreach ( get_field( 'storelist' ) as $store ) : ?>
<div class="bookdata">
<div class="storename">
<?php echo get_the_title( $store->ID );?>
</div>
<div class="bookinfo">
<?php echo $bookinfo; ?>
</div>
<div class="clickbtn">
<a href="<?php echo strip_tags( get_field( 'storelink', $store->ID ) ); ?>"><?php echo $bookcode; ?></a>
</div>
</div><!-- .bookdata -->
<?php endforeach; ?>
</div><!-- .bookindex -->
<?php endwhile; ?>
Edit 2: Clearly I'm not getting exactly how you're looking to echo the links, but the answer to the original question ("why is $storelink
only correct for the last iteration of the $storelist
loop?") remains the same - the variable is being overwritten multiple times without anything being done with it in-between iterations.