A WordPress shortcode is a snippet of code that can be put anywhere in the website to perform dynamic features such as showing photo galleries, audio players, recent blog posts, or custom posts types, etc. Long story short you can display any kind of functionality on your WordPress website with the help of shortcode.
In this article, we are going to create a shortcode that will fetch 3 recent posts (Title & Featured Image) from our blog post. And wherever we will put that shortcode on our website those 3 recent blog posts will be shown.
Code
Place the following code in your functions.php file.
add_shortcode('get3-blogposts', 'getwpweb_shortcode_function_init');
function getwpweb_shortcode_function_init(){
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
'order' => 'ASC',
);
$getwpweb_sc = '';
$loop = new WP_Query( $args );
$getwpweb_sc .='<div class="profilesContainer">';
while ( $loop->have_posts() ) {
$loop->the_post();
$getwpweb_sc .='<div class="singleProfile">';
$getwpweb_sc .= get_the_post_thumbnail();
$getwpweb_sc .='<h2>'. get_the_title() .'</h2>';
$getwpweb_sc .='</div>';
}
$getwpweb_sc .='</div>';
wp_reset_query();
return $getwpweb_sc;
}
Add the following CSS in your style.css file.
.profilesContainer {
display: flex;
justify-content: space-between;
text-align: center;
}
.singleProfile img{
margin-bottom: 10px;
}
Now call the shortcode in your website through Gutenberg shortcode block or simply type the word in the big brackets example:
[ your_shortcode ] or see the image below.
Final Output
TADAAAAA! This is the final output when you put the shortcode on your website. The 3 pictures are featured images and below them are their titles.
How to Add a Shortcode in WordPress Theme Files
<?php echo do_shortcode("[your_shortcode]"); ?>
Code Breakdown & Explanation
First of all in order to create a shortcode we need to add call a WordPress function of add_shortcode which takes 2 arguments.
- Name of the shortcode.
- Name of the function in which you will write the functionality which shortcode performs.
Now create the function and start writing your functionality. Define your “post type” and “post per page”. The post type can be a custom post type as well as simply write the name of the post type. We are using the generic blog post type. And for the number of posts, we are using 3 as we want to display 3 posts. Now we create a variable and in that variable, we write all of our functionality. You cannot write basic PHP in shortcode you have to do everything in the variable. After that, we use the WordPress famous while loop and call the featured image and title function in it which will fetch the featured image and title of the post for us. And in the end, we will return our defined variable and that’s it.
Reader Interactions