Advertise on Site! You can Advertise on our site. Find out More

How can you show the latest post from every category in wordpress homepage

Many people want to show the latest posts from there selected categories or all categories on home page.
I this article I will show how easily you can achieve this.
Please following code in your home page which is your theme’s index.php file.

<?php
$categories=get_categories($all_categories);
 foreach($categories as $category) {
 $post_args=array(
 'showposts' => 1, // you can fetch number of articles from each category
 'category__in' => array($category->term_id),
 'caller_get_posts'=>1
 );
 $posts=get_posts($post_args);
 if ($posts) {
 echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
 foreach($posts as $post) {
 setup_postdata($post); ?>
 <div>
 <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
 <?php the_title(); ?></a></p>
 <p><?php the_excerpt(); ?>
 </div>
 <?php
 } // foreach($posts
 } // if ($posts
 } // foreach($categories
?>

if you want to show the posts from specific articles then use following code.

<?php
$selected_categories=array(
 'include' => '1,4,9',
 'order' => 'ASC'
 );

$categories=get_categories($selected_categories);
 foreach($categories as $category) {
 $post_args=array(
 'showposts' => 1, // you can fetch number of articles from each category
 'category__in' => array($category->term_id),
 'caller_get_posts'=>1
 );
 $posts=get_posts($post_args);
 if ($posts) {
 echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
 foreach($posts as $post) {
 setup_postdata($post); ?>
 <div>
 <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
 <?php the_title(); ?></a></p>
 <p><?php the_excerpt(); ?>
 </div>
 <?php
 } // foreach($posts
 } // if ($posts
 } // foreach($categories
?>
4 Comments

Add a Comment

Your email address will not be published. Required fields are marked *