Listing subpages title and content and styling the first iteration differently

So for now, every iteration looks the same and it’s been a while since I dealt with php so could you help me?

   <?php
$pages = get_pages('child_of='.$post->ID.'&sort_column=post_date&sort_order=desc');
$count = 0;
foreach($pages as $page)
{
    $content = $page->post_content;
    if(!$content)
        continue;
    if($count >= 2)
        break;
    $count++;
    $content = apply_filters('the_content', $content);
?>
    <div id="<?php echo $page->post_title ?>">
      <h2><?php echo $page->post_title ?></h2>
    <?php echo $content ?>
      </div>
<?php
}
  ?>

I’ve look there and there and found that I coud Use something like this

<?php foreach ($pages as $page) : start_wp(); ?>
    <?php if ($i == 1) : ?>
 //first iteration
   <?php else : ?>
//the rest

Related posts

2 comments

  1. you should use $wp_query to retrieve pages and posts because it’s the most efficient way and you can differentiate the loop with $current_post parameter which returns the index of the loop.

    It works like this

    <?php 
    
        $args = array (
            'posts_per_page' => -1, //Showing all the pages
            'post_type' =>  'page', //Retrieving pages not posts.
            'post_parent'   => $post->ID
            );
    
        $the_query = new WP_query($args);
        while($the_query->have_posts()):
            $the_query->the_post();
                if ($the_query->current_post == 0){ // For first child page only
                                echo 'FIRST POST IS: ';
                    the_title();
                }
                else{   //For rest of the pages
                    the_title();
                }
        endwhile;
        wp_reset_postdata();
    
    ?>
    

    Have a look at the if structure. You can use the post index current_post like that.

    You can customize the query the way you like.

    Reference: WP_Query Codex

  2. I think this is more of a PHP question than a wordpress question. If I have understood clearly you want the first result of the loop to be styled differently from the others. This is how I would do it.

    <?php
    $pages = get_pages('child_of='.$post->ID.'&sort_column=post_date&sort_order=desc');
    
    $count = 0;
    
    foreach($pages as $page) {
    
    $content = $page->post_content;
    $content = apply_filters('the_content', $content);
    
    if($count=0) { ?>
    
         //markup for first iteration
    
      <?php  } else { ?>
    
          //markup for remaining iterations
    
       </php }
    
        $count++;
    }
    
      ?>
    

Comments are closed.