How to create Shortcodes in WordPress

Shortcodes are very awesome feature of WordPress. Shortcodes are being used in most of the modern WordPress themes specially the paid themes. It allows your client to add content easily with out any technical knowledge.  You can create shortcode using add_shortcode() function.

<?php add_shortcode( $tag , $func ); ?>

The first parameter $tag (Shortcode tag to be searched in post content) is the name of your shortcode  and $func is the name of the function in which you will do your coding part. In this article we will create a shortcode that displays the latest posts added by user.

How to create a shortcode?

Let’s start by adding the following line to your function.php file.

add_shortcode('latest_posts', 'latest_post_display');

Then prepare a wp_query that will display latest posts.

 // The Query
 $the_query = new WP_Query( $args );

 // The Loop
 if ( $the_query->have_posts() ) {
 echo '<ul>';
 while ( $the_query->have_posts() ) {
 $the_query->the_post();
 echo '<li>' . get_the_title() . '</li>';
 }
 echo '</ul>';
 } else {
 // no posts found
 }
 /* Restore original Post Data */
 wp_reset_postdata();

Now create the function that will run when shotcode is found in content.

in our case its latest_post_display().  Then  prepare parameters for shortcode.

extract( shortcode_atts( array(
 'count' => 3, // By default post count will be 3
 ), $attr ) );

Your shortcode is all ready. Now lets put all code together which will look like.

 /*
 * Shortcode that displays latest posts
 */
add_shortcode('latest_posts', 'latest_post_display');
function latest_post_display($attr, $content=null){
 extract( shortcode_atts( array(
 'count' => 3, // By default post count will be 3
 ), $attr ) );
 
 
 $args = array(
 'post_type' => 'post',
 'posts_per_page' => $count
 );
 // The Query
 $the_query = new WP_Query( $args );

 // The Loop
 if ( $the_query->have_posts() ) {
 echo '<ul>';
 while ( $the_query->have_posts() ) {
 $the_query->the_post();
 echo '<li>' . get_the_title() . '</li>';
 }
 echo '</ul>';
 } else {
 // no posts found
 }
 /* Restore original Post Data */
 wp_reset_postdata();
}

How to use this shortcode ??

You can add this shortcode in your page anywhere. Add following to your page.

[latest_posts count="5"]

If you want to use this shortcode in your template i.e. PHP file. Then use following method.

<?php echo do_shortcode('[latest_posts count="5"]'); ?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s