Hi there Developers,
Today, we are going to look into how we can add custom shortcodes in WordPress with attributes, Now that we already know how shortcode works in our previous blog on how we can add custom shortcodes in WordPress
So we’ll directly dive into the coding part, as we already done the theory part in previous blog.
Define Shortcode:
We can define our custom shortcode in our functions.php, like we have done here:
/** * Add a custom 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(){
// 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 with custom attributes.
<?php
// add_shortcode('name of the shortcode', 'call back function of the shortcode');
add_shortcode('av-display-posts', 'av_display_posts');
function av_display_posts( $attr ) {
$num_of_posts = 9;
if( array_key_exists( 'postcount', $attr ) ) {
// $attr variable having array of attributes passed through shortcode, check if postcount key exists
$num_of_posts = $attr['postcount'];
// set number of posts per page to attribute value
}
$output = '';
// Output variable which will return the HTML
$args = array( 'post_type'=> 'posts', 'posts_per_page' => $num_of_posts, '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:
The $attr
variable passed as a parameter contains the array of attributes passed in shortcode
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 postcount=3]' );
The Result of this is like: