How do you stop echo of multiple values with 'foreach' in PHP?

Go To StackoverFlow.com

-4

How do you when using custom fields in Wordpress echo just the first value using foreach?

Currently the code is:

    <?php for(get_field('venue_event') as $post_object): ?>
        <a href="<?php echo get_permalink($post_object); ?>"><?php echo get_the_title($post_object) ?></a>
    <?php endforeach; ?>

This takes the field from the wordpress page (the field is a link to another page), creates a link to that page using get_permalink but when I want to echo the page title it does it, but then it also echos all other values that are not needed.

2012-04-04 18:16
by Aaron EA


2

If you just want the execute the first iteration of the loop, try this:

<?php foreach(get_field('venue_event') as $post_object): ?>
    <a href="<?php echo get_permalink($post_object); ?>"><?php echo get_the_title($post_object) ?></a>
<?php break; ?>
<?php endforeach; ?>
2012-04-04 18:18
by Cal
Break works, and now everything is fine, but left the each off on the first line, so make that 'foreach' instead of 'for' and it all works - Aaron EA 2012-04-04 18:27
Updated. I was wondering if/how that was working for you. Please "accept" this answer if it has helped you - Cal 2012-04-04 23:23


0

you can just add

$counter = 0;
<?php for(get_field('venue_event') as $post_object): ?>
    $counter++;
    if($counter == 1)
     {
    <a href="<?php echo get_permalink($post_object); ?>"><?php echo get_the_title($post_object) ?></a>
     }

<?php endforeach; ?>
2012-04-04 18:19
by magicianiam
if($counter = 1) will execute every tim - nathanjosiah 2012-04-04 18:26
edited, sorry for that typo - magicianiam 2012-04-04 18:28


0

Wouldn't it then be easier just to use the first element of the returned array? Maybe Wordpress offers other filters that return the the page's title only.

2012-04-04 18:21
by Dominik M.
Ads