<?php
/**
* Snippet to show how to add alternate classes to a div within a foreach loop.
* Author: Gemma Plank
* Author URL: https://makedo.net
*/
// Get current page ID.
$page_id = get_the_ID();
// Array of class name modifiers.
// These affect the background colour of each panel.
$colours = array(
'',
'service-panel--white',
'service-panel--red',
);
// Initiate our counter.
// This allows us to stop when we reach the maximum number of colour classes & restart.
$i = 0;
// Create args for loop below.
$services_args = array(
'post_parent' => $page_id,
'post_type' => 'any',
'numberposts' => -1,
'post_status' => 'any',
);
// Get child posts based on the above args.
$child_services = get_children( $services_args );
// For each post/page within the array.
foreach ( $child_services as $child_service ) {
// Store each panel class based on position within our $colours array.
$panel_class = $colours[ $i ];
// Print opening div with new modifier class name printed.
echo '<div class="service-panel-link' . esc_attr( $panel_class ) . '">';
// Print post title.
echo esc_html( $child_service->post_title );
// Print closing div tag.
echo '</div>';
// Increment our counter.
$i++;
// Reset our counter back to zero when our limit of 2 is reached.
// This will need to change if we alter the number of classes inside the $colours array.
// NOTE: its technically 3 as we start from 0 not 1.
if ( $i > 2 ) {
$i = 0;
}
}
?>