...

View Full Version : Extra class in last of while loop?



wyclef
09-07-2011, 11:25 PM
Hey, using advanced custom fields for wordpress which has a repeater field function as follows. i'm interested in a way to add a special class to the last P tag in the array. Not sure how.


<?php while(the_repeater_field('test')): ?>
<p><?php the_sub_field('test-sub'); ?></p>
<?php endwhile; ?>

kbluhm
09-08-2011, 08:19 AM
This solution may seem a bit long-winded following the 3 lines of code above, but it is only because WordPress' functions offer little control for honest developers and seem to cater more toward designers. ;)

This is untested, but it should work as desired:


<?php

$sub_fields = array();

// Capture the output from `the_sub_field()` to an array
while ( the_repeater_field( 'test' ) )
{
ob_start();
the_sub_field( 'test-sub' );
$sub_fields[] = ob_get_clean();
}

?>

<?php while ( $sub_field = array_shift( $sub_fields ) ): ?>
<?php echo empty( $sub_fields ) ? '<p class="last-item">' : '<p>'; ?>
<?php echo $sub_field; ?>
</p>
<?php endwhile; ?>

wyclef
09-08-2011, 06:05 PM
thanks a lot. this does work. it does seem a bit much but wordpress is a pita so...

wyclef
09-08-2011, 06:23 PM
what if you were to have different the_sub_field( 'test-sub' ); within the same while loop? like the_sub_field( 'test-sub' ); and the_sub_field( 'test-test' ); and the_sub_field( 'test-pro' );

kbluhm
09-08-2011, 06:24 PM
Care to elaborate? I'm definitely no WP guru... not sure where you're headed with that one.

wyclef
09-08-2011, 06:45 PM
trying to do something with more fields in the loop like follows


<?php

$sub_fields = array();

// Capture the output from `the_sub_field()` to an array
while ( the_repeater_field( 'test' ) )
{
ob_start();
the_sub_field( 'test-sub' );
$sub_fields[] = ob_get_clean();
}

?>

<?php while ( $sub_field = array_shift( $sub_fields ) ): ?>
<?php echo empty( $sub_fields ) ? '<p class="last-item">' : '<p>'; ?>
<?php echo $sub_field; ?>
</p>
<span><?php the_sub_field('test-sub-new'); ?></span>
<a href="<?php the_sub_field('test-sub-link'); ?>"></a>

<?php endwhile; ?>

mindblaster
09-09-2011, 11:01 AM
thank you so much for sharing :)

wyclef
09-09-2011, 04:59 PM
yea, but the additional sub fields i added don't work



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum