Many people want to show wordpress show latest post from each category posts from there selected categories or all categories on home page. Here we given code snippet for this.
I this article I will show how easily you can achieve this.
wordpress show latest post from each category
Please following code in your home page which is your theme’s index.php file.
<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1">php</span>--> $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 '</pre> Category: sprintf( __( " href="' . get_category_link( $category->term_id ) . '">name ) . '" ' . '>' . $category->name.'</pre> <pre> ';foreach($posts as $post) {</pre> <pre> setup_postdata($post); ?></pre> <div> php the_title_attribute(); ?>" href="<!--?php the_permalink() ?-->" rel="bookmark"> <!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1">php</span> the_title(); ?--> <!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1">php</span> the_excerpt(); ?--> </div> <pre> <!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1">php</span>--> } // foreach($posts } // if ($posts } // foreach($categories ?-->
if you want to show the posts from specific articles then use following code.
<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1">php</span>--> $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 '</pre> Category: sprintf( __( " href="' . get_category_link( $category->term_id ) . '">name ) . '" ' . '>' . $category->name.'</pre> <pre> ';foreach($posts as $post) {</pre> <pre> setup_postdata($post); ?></pre> <div> php the_title_attribute(); ?>" href="<!--?php the_permalink() ?-->" rel="bookmark"> <!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1">php</span> the_title(); ?--> <!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1">php</span> the_excerpt(); ?--> </div> <pre> <!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1">php</span>--> } // foreach($posts } // if ($posts } // foreach($categories ?-->
Very helpful article. I have been looking for a way to do this all my life. Thanks for the codes.
What about if I choose certain categories but I don’t want one of the child-categories of one of these chosen categories?
How do I exclude this category?
I tried to add ‘exclude’ => ’35’, But that does not seem to work.
Any thoughts? 🙂