Yogesh Chauhan's Blog

How to create a Recent Posts function in WordPress?

in WordPress on July 26, 2021

Similar Post

How to display random posts in WordPress?

I am going to make a few changes in the same function we used for random posts.

I have not included the CSS part so you’ll still need to design it the way you want.

Step 1: Arguments

Let’s create an array variable named as $args and add the arguments to it.

The post_type can be post, page or any other custom post type.

With posts_per_page argument you can decide how many posts you want to fetch.


$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 10, 
    );
...

Step 2: WP_Query

Let’s create an instance of WP_Query and pass the $args array.


...
$query = new WP_Query( $args );
...

Step 3: Fetch the posts

Let’s check if there are any posts in the $query variable and if so, save those posts with an HTML code in a PHP string.

Also, we will have an else condition too in case of no posts to fetch. In that case, we can just show some message that indicates that there are no posts to display.


...
if ( $query->have_posts() ) {
    $recent_posts .= '<section>';
        while ( $query->have_posts() ) {
            $query->the_post();
            $recent_posts .= '<a href="'. get_permalink() .'">'. get_the_title() .'</a>';
        }
    $recent_posts .= '</section>';
    wp_reset_postdata();
} else {
    $recent_posts .= '<p>Nothing to show</p>';
}
...


Note that there is wp_reset_postdata() in the if condition.

Since we’re using a specific query, we are affecting the $post global but in the loop there is not much we can do.

So, after the loop we need to use wp_reset_postdata() to restore the $post global to the current post in the main query.

Optional: Show Post Excerpt

If you want to show Post Excerpt with the link, you can add this line after the link.


...
$recent_posts .= the_excerpt(__('(more…)'));
...

That will attach an excerpt in the $recent_posts variable.


Step 4: Function and a shortcode

Let’s write the complete function by using the code chunks above.


function yc_recent_posts() { 

    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => 10,
        );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        $recent_posts .= '<section>';
            while ( $query->have_posts() ) {
                $query->the_post();
                $recent_posts .= '<a href="'. get_permalink() .'">'. get_the_title() .'</a>';
            }
        $recent_posts .= '</section>';
        wp_reset_postdata();
    } else {
        $recent_posts .= '<p>Nothing to show</p>';
    }
    
    return $recent_posts; 
}

add_shortcode('yc-recent-posts','yc_recent_posts');
add_filter('widget_text', 'do_shortcode'); 


You can just call the function above using the shortcode [yc-recent-posts], and it will display 10 recent posts.

Using do_shortcode we can execute the shortcode inside a widget.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to select an element using its ID without the high specificity of the ID selector?CSSHow to define variables in SCSS (Sass)?SCSSMicroservices vs Monolithic ArchitectureMiscellaneousHow to Access a Global Variable From Inside a Function in PHP?PHPFlash of Invisible Text and Mitt Romney Web Font ProblemCSSHow to get Current Year, Month and Date in JavaScript?JavaScript