Home

How to create shortcode to show the latest posts

How to create shortcode to show the latest posts
Like Tweet Pin it Share Share Email

[myad1]  With the help of the WordPress query, we can get the latest post in the descending order or in the ascending order but we can not use the same query multiple times on each page or on the sidebar. We can use the shortcode to get the latest post in any order.

Below I have shown the simple and easy example of a shortcode to get the latest 5 posts in the descending order. Create a shortcode using a hook with an add_shortcode function. Place it in the functions.php file.

<?php 
    add_shortcode("unity_latest_post", "unity_latest_post_function");
?>

In the above code, unity_latest_post is shortcode which you have to use it where you want to show the latest posts. unity_latest_post_function this is function name in which you have to add the WordPress query to show the latest posts.

Next copy the below code and paste in your functions.php file. In the above code, I have shown the latest 5 posts. You can change it as per your requirement.

The order is a descending order and you can change to ascending or random.  In the result, I have shown only title and the published date. The class is added to each you can design as per your need.

<?php

function unity_latest_post_function(){
	ob_start();
	?>
    <ul class="unity_latest_post_listing">
        <?php
        $args = array(  'post_type' => 'posts', 
	            'posts_per_page' => 5,
	            'orderby' => 'desc',
	        );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post(); global $post;
                    ?>
                    <li class="">
                    	<a href="<?php the_permalink();?>" class="unity_latest_post_widget_title" style="text-decoration: none !important;">
                    		<?php the_title(); ?>
                        	
                        </a>
                        <div class="unity_unity_latest_post_date"><?php the_date('dS M, Y'); ?></div>
                        
                    </li>

            <?php endwhile; ?>
            <?php wp_reset_query(); ?>
        </ul>
        <?php
        $output = ob_get_contents();   
        ob_end_clean();   
        return $output;

}

?>

You can add more fields in the code like featured images, author name, category name etc.

After setup, use  [unity_latest_post] shortcode in the pages or in the sidebar to display the latest posts as shown in the below screenshot.

[myad1]

create shortcode to show the latest posts
create a shortcode to show the latest posts

Please do let me know if you want more fields in the shortcode. Give me your feedback via comments.

Thanks for reading our article. What Next?

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *

3 × four =