简体   繁体   中英

Replace wordpress loop in the front page

I am trying publish a blog using the theme twenty seventeen , but want a different approach for the front page. Instead of display the last posts published, I want list all categories with the excerpt for the most recent post in that category.

For this, I need replace this code:

<main id="main" class="site-main" role="main">
  <?php
  if ( have_posts() ) :
    while ( have_posts() ) :
      the_post();
      get_template_part( 'template-parts/post/content', get_post_format() );
    endwhile;
    the_posts_pagination( ... );
  else :
    get_template_part( 'template-parts/post/content', 'none' );
  endif;
  ?>
</main><!-- #main -->

in the index.php file with one that iterate over each category I have, displaying the most recent post in this category (the name of the category should be displayed too, above the post content).

I have a very minimum experience with php. And I am looking for a solution that not requires edit the code for index.php in the Edit theme option on wordpress, since a update on the theme would require that I keep redoing this task.

Anyone can give a hint of how to accomplish that?

Use the below code and replace the content with your template structure.

$cats = get_the_category();

foreach($cats as $cat) {
    $args = array('numberposts' => 1, 'category' => $cat->term_id);
    $post = get_posts($args);

    echo 'Post under Category: '.$cat->name;
    echo get_the_excerpt($post);

    echo '<br>';
}

I did not wanted to run a while loop inside the foreach is this would be a very bad practice. This is the basic code, just replace the html as per your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM