Support » Themes and Templates » Problem with foreach loop

  • Resolved jrcollins

    (@jrcollins)


    I’m customizing my theme’s category template to display the current category’s child categories instead of the posts from that category.

    The category template links to another template file (content-grid.php) which generates the dynamic post/category content.

    The only way I can get it to work is by including all the code on the category template.

    This is how the original category template links to content-grid.php (I’m only showing the relevant code):

    echo '<div class="row">';
    while ( have_posts() ) : the_post();
    $count++;
    get_template_part( 'template-parts/content-grid' );
    if ( $count % 2 == 0 ) {
    echo '</div>';

    In my customized template I’ve changed the standard loop to a “foreach” loop and link to the same file like this:

    echo '<div class="row">';
    foreach ( $child_categories as $child ){
    $count++;
    get_template_part( 'template-parts/content-grid' );
    if ( $count % 2 == 0 ) {
    echo '</div>';
Viewing 1 replies (of 1 total)
  • I solved this by replacing get_template_part( 'template-parts/content-grid' ); with include( locate_template( 'template-parts/content-grid.php' ) );

Viewing 1 replies (of 1 total)
  • The topic ‘Problem with foreach loop’ is closed to new replies.