[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.
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.
$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;
<a href="<?php the_permalink();?>" class="unity_latest_post_widget_title" style="text-decoration: none !important;">
<?php the_title(); ?>
<div class="unity_unity_latest_post_date"><?php the_date('dS M, Y'); ?></div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
$output = ob_get_contents();
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.
Please do let me know if you want more fields in the shortcode. Give me your feedback via comments.