Hi there Developers,
Today, we are going to look into how we can add custom shortcodes in WordPress, Let’s start with the some theory, which obviously is boring…:-p
What is Shortcode?
Shortcode is a feature that can be added to websites. It’s basically written inside two square brackets e.g; [demo-shortcode]. This Shortcode can be used anywhere in the website. In WordPress Editor there is an option to shortcode, it’s called shortcode block.
WordPress provides a lot of shortcodes that can be used as per the requirement. You can check it on WordPress Codex as well.
Now We can jump into the Interesting Part… 🙂
Define Shortcode:
We can define our custom shortcode in our functions.php, like we have done here:
/**
* Add a custom shortcode - AV
*/
// add_shortcode('name of the shortcode', 'call back function of the shortcode');
add_shortcode('av-display-posts', 'av_display_posts');
function av_display_posts(){
// Do something here...
}
Here we have defined our shortcode using WordPress hook add_shortcode
And given a callback function to write our logic.
Here we are going to display posts on our website using a shortcode.
// add_shortcode('name of the shortcode', 'call back function of the shortcode');
add_shortcode('av-display-posts', 'av_display_posts');
function av_display_posts(){
$output = ''; // Output variable which will return the HTML
$args = array(
'post_type' => 'posts',
'posts_per_page' => 3,
'post_status' => 'published',
);
$query = new WP_Query( $args );
if($query->have_posts()){
while( $query->have_posts()){
$query->the_posts();
$output .= '<div class="col-md-4">
<img src="'. get_post_thumbnail_url() .'"
<h1>'. get_the_title() .'</h1>
<p>'. get_the_content() .'</p>
</div>'; // This will append all the posts to a variable
}
wp_reset_query();
}
return $output; // Returns posts data
}
Code Breakup:
First we queried the post using WP_Query class, then we looped the post data and set it according to our HTML.
Now all we have to do is to paste the shortcode to the webpage, we need to display our posts like:
/* Call Shortcode anywhere in the page */
echo do_shortcode( '[av-display-posts]' );
The Result will be like:
Now that’s the end of this article. Did you find this article helpful? If they have worked for you, and you enjoyed this article, feel free to share it with your friends and colleagues!
Sharing is caring!