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!

Java实现的提取关键词算法和应用实例随着互联网时代的到来,海量的文本数据对人们的获取和分析造成了很大的困难,因此需要进行关键词提取等自然语言处理技术的研究和应用。关键词提取是指从一段文本中提取出最能代表该文本主题的单词或短语,为文本分类、检索、聚类等任务提供支持。本文介绍了Java实现的几种关键词提取算法和应用实例。一、TF-IDF算法TF-IDF是一种从

在Go中实现代码复用有两种主要方法:函数:将重复任务封装在函数中,并在整个项目中重用。包:将相关的代码组织在包中,允许在程序的不同部分重用代码。

遵循Golang函数命名约定的好处有:确保函数命名一致,提高可读性。增强可预测性,方便理解函数用途。支持IDE自动补全,节省时间。简化调试,便于隔离问题。

ECharts词云图:如何展示数据关键词,需要具体代码示例引言:随着大数据时代的来临,我们面临的一个重要问题就是如何有效地从海量数据中提取出有用的信息。而关键词的提取就是其中一种常用的方法。在展示关键词时,词云图是一种非常直观且具有艺术性的方式,可以使人们一眼就能快速理解数据的特点和关键词的重要程度。本文将介绍如何使用ECharts来实现词云图的展示,并提供

Go语言中的os.Rename函数可方便地重命名文件或目录,更新文件或目录名称而不丢失数据。它需要两个参数:oldpath(当前路径)和newpath(新路径)。该函数会覆盖现有目标,且只能重命名同一文件系统中的文件或目录。

PHP开发中如何实现百度文心一言随机语句的关键词提取功能?百度文心一言是一种随机展示的句子,常用于网站的首页、登录页等地方,电影《你的名字》中也应用了这个功能。而其中的关键词提取功能,可以使展示的句子与网站的内容更加相关,增加用户的阅读体验。接下来,我们将介绍如何使用PHP开发来实现这一功能。首先,我们需要获取百度文心一言的API。在百度开放云平台(http

C语言是一种被广泛应用于软件开发和系统编程的高级程序设计语言。它被设计成一种通用的、面向过程的语言,以其简单易学、执行速度快以及可移植性强而著称。C语言有着丰富的构成成分,这些成分相互配合,组成了一个完整的程序。在C语言程序中,最基本的单位是字符和标识符。字符是构成程序文本的最小单位,它可以是字母、数字、符号等。而标识符则是由字母、数字和下划线组成的命名,用

编写和优化自定义Golang函数的技巧对于提升应用程序性能至关重要:缓存函数结果以避免重复计算。使用并发并行执行昂贵的操作。使用指针避免大结构和切片的复制开销。优化循环避免不必要的变量声明和高效的循环构造。利用管道实现并行处理。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
