jenhuls
1/13/2016 - 5:22 PM

WordPress: Loop that calculates total hours times hourly rate for invoice containing an ACF repeater field.

WordPress: Loop that calculates total hours times hourly rate for invoice containing an ACF repeater field.

<!-- Start ACF repeater field -->
<?php if( have_rows('invoice_services') ): //this is the name of the repeater field itself ?>

		<div class="row">
			<div class="large-12">
				<table class="services">
					<tr>
						<th>Description</th>
						<th>Hours</th>
						<th>Hourly Rate</th>
						<th>Total</th>
					</tr>

	<?php
		$hours = 0; // This allows counting of each sub_field
		while( have_rows('invoice_services') ): the_row(); 

		// vars
		setlocale(LC_MONETARY, 'en_US'); // For formatting money_format
		$service_name = get_sub_field( 'invoice_service_name' );
		$service_quantity = intval(get_sub_field( 'invoice_service_quantity' ) );
		$service_amount = money_format( '%i', get_sub_field( 'invoice_service_amount' ) );
		$line_total = get_sub_field('invoice_service_quantity' ) * money_format('%i', get_sub_field( 'invoice_service_amount' ) );
		$hours += intval( get_sub_field('invoice_service_quantity' ) ); //intval: Get the integer value of a variable
		$hours_amount = get_sub_field( 'invoice_service_amount' );
		
	?>

			<tr id="services" class="service">
	
				<?php if( $service_name ): ?>
					<td class="name"><?php echo $service_name; ?></td>
				<?php endif; ?>
	
				<?php if( $service_quantity ): ?>
					<td class="quantity"><?php echo $service_quantity; ?></td>
				<?php endif; ?>
	
			    <?php if( $service_amount ): ?>
					<td class="amount">$<?php echo $service_amount; ?></td>
				<?php endif; ?>
				<?php if( $line_total ): ?>
					<td class="total">$<?php echo $line_total; ?></td>
				<?php endif; ?>
			</tr>

	<?php endwhile; ?>
			<tr>
				<?php
				// This is what does the multiplication of total hours and the hourly rate
					$sum_hours = $hours * $hours_amount;
				?>
				<td class="total-th text-right" colspan="3">Invoice Total:</td>
				<td class="total">$<?php echo $sum_hours; ?></td>
			</tr>
		</table>
	</div>
</div>

<?php endif; ?>
<?php endwhile;?>