Show latest posts per category
By default, your main WordPress blog page displays your most recent posts in descending date order. However, if you use categories on your site and your readers want to see new content in each category, you may want your blog pages to look different.
In this tutorial I will show you how to do this. I'll show you how:
- Identify all categories on your blog
- Show the latest post for each post, or the featured image if the post has one
- Ensure posts in multiple categories are not duplicated
- Add some styling to make it look good
What do you need
To follow this tutorial you will need:
- Development installation of WordPress.
- Some posts and categories have been set up. I used the data example from the WordPress theme unit test data.
- A theme. I will create a subtopic of the "Twenty Four" topic.
- Code Editor.
Set theme
The first step is to set up the theme. I will create a child theme of the Twenty-Four theme with just two files: style.css
and index.php
.
This is my stylesheet:
/* Theme Name: Display the Most Recent Post in Each Category Theme URI: http://code.tutsplus.com/tutorials/display-the-most-recent-post-in-each-category--cms-22677 Version: 1.0.0 Description: Theme to accompany tutorial on displaying the most recent post fort each term in a taxonomy for Tutsplus, at http://bitly.com/14cm0yb Author: Rachel McCollin Author URI: http://rachelmccollin.co.uk License: GPL-3.0+ License URI: http://www.gnu.org/licenses/gpl-3.0.html Domain Path: /lang Text Domain: tutsplus Template: twentyfourteen */ @import url('../twentyfourteen/style.css');
I will come back to this file later to add styles, but for now WordPress just needs to recognize the child theme.
Create index file
Since I want my main blog page to display the latest posts in each category, I will create a new index.php
file in my child theme.
Create an empty index.php file
First, I'll copy the index.php
file from 24 and edit out the loops and other stuff so it looks like this:
<?php /** * The main template file. * * Based on the `index.php` file from TwentyFourteen, with an edited version of the `content.php` include file from that theme included here. */ ?> <?php get_header(); ?> <div id="main-content" class="main-content"> <?php if ( is_front_page() && twentyfourteen_has_featured_posts() ) { // Include the featured content template. get_template_part( 'featured-content' ); } ?> <div id="primary" class="content-area"> <div id="content" class="site-content" role="main"> </div> </div> <?php get_sidebar( 'content' ); ?> </div> <?php get_sidebar(); ?> <?php get_footer(); ?>
Identification Category
The first step is to determine the categories in your blog. Then open the <div id="content"> tag and add the following content:
<pre class='brush:php;toolbar:false;'><?php
$categories = get_categories();
foreach ( $categories as $category ) {
}
?>
</pre>
<p>This uses the <code class="inline">get_categories()
function to get the list of categories in the blog. By default this will be fetched alphabetically and will not contain any empty categories. This works for me so I won't add any extra parameters.
Then I use foreach ( $categories as $category ) {}
to tell WordPress to run each category in turn and run the code inside the curly brackets. The next step is to create a query that will be run against each category.
Define query parameters
Now you need to define the parameters of the query. Add the following within curly brackets:
$args = array( 'cat' => $category->term_id, 'post_type' => 'post', 'posts_per_page' => '1', );
This will only get one post in the current category.
Run query
Next, insert the query using the WP_Query
class:
$query = new WP_Query( $args ); if ( $query->have_posts() ) { ?> <section class="<?php echo $category->name; ?> listing"> <h2 id="Latest-in-php-echo-category-name">Latest in <?php echo $category->name; ?>:</h2> <?php while ( $query->have_posts() ) { $query->the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class( 'category-listing' ); ?>> <?php if ( has_post_thumbnail() ) { ?> <a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail( 'thumbnail' ); ?> </a> <?php } ?> <h3 class="entry-title"> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </h3> <?php the_excerpt( __( 'Continue Reading <span class="meta-nav">→</span>', 'twentyfourteen' ) ); ?> </article> <?php } // end while ?> </section> <?php } // end if // Use reset to restore original query. wp_reset_postdata();
This will output the featured image, title and excerpt for each article, each included in a link.
Let’s see what it looks like now:
As you can see, there is a problem. My page shows the latest posts in each category, but it is a duplicate post because sometimes a post will be the latest post in multiple categories. Let's solve this problem.
Avoid duplicate posts
Above the line that adds the get_categories()
function, add the following lines:
$do_not_duplicate = array();
This will create an empty array called $do_not_duplicate
which we will use to store the ID of each post output and then check to see if the ID of any post queried later is in that array.
Next, add a new row below the query options, so the first two rows look like this:
<?php while ( $query->have_posts() ) { $query->the_post(); $do_not_duplicate[] = $post->ID; ?>
This will add the ID of the current post to the $do_not_duplicate
array.
Finally, add a new parameter to the query parameters to avoid outputting any posts in this array. Your argument now looks like this:
$args = array( 'cat' => $category->term_id, 'post_type' => 'post', 'posts_per_page' => '1', 'post__not_in' => $do_not_duplicate );
This uses the 'post__not_in'
parameter to look up the post ID array.
Save your index.php
file and view your blog page again:
This is better! Now your post is no longer a duplicate.
Add style
Currently, the content is a bit spread out, with the featured image sitting above the post title and excerpt. Let's add some styling to make the image float to the left.
In your theme’s style.css
file, add the following:
.listing h2 { margin-left: 10px; } .category-listing img { float: left; margin: 10px 2%; } .category-listing .entry-title { clear: none; }
Now the content fits the page better and the layout is better:
Adapt this technology to different content types
You can adapt this technique to handle different content types or taxonomies. For example:
- If you want to use custom taxonomy terms instead of categories, you can replace
get_categories()
withget_terms()
and change the'cat'
query parameter to find classification terms. - If you are using a different post type, you can add similar code to your template file to display that post type, replacing the
'post_type' => 'post'
parameter with your query parameter Your post type. - If you want to create a separate page within your main blog page to display the latest posts of any post type for a given category, you can create a category archive template and add an adapted version of this code to it. 李>
- You can go a step further and use this technique with multiple taxonomies or multiple post types, using nested
foreach
statements to run multiple loops. - You can add the above code to your
single.php
page to display links to the latest posts in each category after the post content. If you do this, you need to add the ID of the currently displayed page to the$do_not_duplicate
array.
Summary
Sometimes it can be helpful to display the latest posts on your blog in another way (rather than simply in chronological order). Here I demonstrate a technique for displaying the latest posts in each category on your blog, ensuring posts are not duplicated in multiple categories.
The above is the detailed content of Show latest posts per category. For more information, please follow other related articles on the PHP Chinese website!

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools
