Recent posts are fine and easy to achieve, and you have many plugins to do that for you. What’s your take about recent pages?
In a recent project, the client felt the need to show recent pages below every page’s content. It was something new, as nobody really asks to display recent pages on their WordPress site.
So, what’s the big deal in displaying recent pages?
Nothing. WordPress API is pretty flexible to display almost any kind of content you wish to on the front-end.
And what does it take to display the recent pages? The below give small PHP code snippet.
PHP to display Recent Pages in WordPress
No more talking, here it is:
function wpcrux_recent_posts( $num ) {
// Prepare variables
global $post;
$html = null;
// Build our basic custom query arguments
$recent_pages_args = array(
'post_type' => 'page',
'posts_per_page' => $num, // Number of recent pages to display
'post__not_in' => array( $post->ID ), // Ensure that the current page is not displayed
);
// Initiate the custom query
$recent_pages = new WP_Query( $recent_pages_args );
// Run the loop and collect data for the matched results
if ( $recent_pages->have_posts() ) {
$html = '<h4>Recent Pages</h4>';
$html = '<ul class="recent-pages">';
while ( $recent_pages->have_posts() ) {
$recent_pages->the_post();
$html.= '<li><a href="' . get_permalink() . '" rel="bookmark noopener" target="_blank">' . get_the_title() . '</a></li>';
}
$html.= '</ul><!-- .recent-pages -->';
}
// Reset the loop
wp_reset_postdata();
// Return the final HTML
return $html;
}
The code is pretty much self-explanatory by itself, if you go through the code comments.
- Prepare a custom query, to request pages only
- Make function take control over the number of recent pages to be displayed
- Remove the addition of current page in that list
It’s a PHP function that asks you just the number of recent pages you want to display.
So, you place the above mentioned code in your theme’s functions.php
(save it) and then in your page.php
template (or anywhere you want the stuff to render), you call the function just like below:
<?php echo wpcrux_recent_pages( 5 ); ?>
Modify the number as per your requirement. I hope this was helpful.