Home > Web Front-end > HTML Tutorial > Show latest posts per category

Show latest posts per category

WBOY
Release: 2023-08-31 11:29:05
Original
794 people have browsed it

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');
Copy after login

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(); ?>
Copy after login

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:

<?php
    $categories = get_categories(); 

    foreach ( $categories as $category ) {

    }
?>
Copy after login

This uses the 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',
);
Copy after login

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>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">&rarr;</span>', 'twentyfourteen' ) ); ?>

            </article>

        <?php } // end while ?>

    </section>

<?php } // end if

// Use reset to restore original query.
wp_reset_postdata();
Copy after login

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:

Show latest posts per category

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();
Copy after login

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;
    ?>
Copy after login

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
);
Copy after login

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:

Show latest posts per category

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;
}
Copy after login

Now the content fits the page better and the layout is better:

Show latest posts per category

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() with get_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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template