Replace “yourcategoryslug” with the specific category slug on line 3.
In the WYSIWYG editor of WordPress, you can now insert the following shortcode to display the recent category posts:
[categoryposts]
Note: It may be necessary to style the recent post widget (using CSS) so that they match your blog’s design.
Display Recent Posts from Specific Category in Template Files
To display recent posts from a specific category in a template file (e.g. sidebar.php, custom.php), add the following code snippet:
<?php $catquery = new WP_Query( 'cat=50&posts_per_page=5' ); ?> <ul> <?php while($catquery->have_posts()) : $catquery->the_post(); ?> <li><h3><a href=" the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3> <ul><li><?php the_excerpt(); ?></li> </ul> </li> <?php endwhile; ?> </ul> <?php wp_reset_postdata(); ?>
The above code displays the title of the post as well as the excerpt. You need to replace “50” with your own category ID number on line 1.
Display Most recent Posts on a Static Homepage or Template File
The following code snippet should be added to a custom page template, then create a WordPress page using the template, and then set the page as the homepage under Settings > Reading.
<?php $args = array( 'numberposts' => 10 ); $lastposts = get_posts( $args ); foreach($lastposts as $post) : setup_postdata($post); ?> <h2><a href=" the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_content(); ?> <?php endforeach; ?>
To display the latest posts, you can also use WP_Query.
Here is a code snippet that displays 10 latest posts with titles and excerpts:
<ul> // Define our WP Query Parameters <?php $the_query = new WP_Query( 'posts_per_page=10' ); ?> // Start our WP Query <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> // Display the Post Title with Hyperlink <li><a href=" the_permalink() ?>"><?php the_title(); ?></a></li> // Display the Post Excerpt <li><?php the_excerpt(__('(more…)')); ?></li> // Repeat the process and reset once it hits the limit <?php endwhile; wp_reset_postdata(); ?> </ul>
Display Recent Posts with Plugins
The WordPress plugin repository has a number of free plugins that offer the same functionality. A better design customization is also possible with these plugins.
- Posts in Page
- Recent Posts Widget Extended
- WP Latest Posts
- Advanced Recent Posts
- Advanced Random Posts Widget
- Author Recent Posts
Source link