WordPress — Power-up Your Blog With WordPress Shortcodes [5 Examples]

Wordpress shortcodes is relatively lesser known but a very powerful Worpress feature. It enables you to create a specific syntax for any repetitive or frequently used words while blogging. All thanks to WordPress Shortcode API, which makes it possible. In technical terms, WordPress shortcodes are used to create a macro code for use in post content.

For example, when creating a WordPress tutorial on your blog, “WordPress” is repeated n number of times. You can create a syntax say [w] for “WordPress” and all you need to do is to type in [w] in HTML editor in place of “WordPress”. The syntax [w] will be replaced by the WordPress when you save the draft. That’s a very simple example, but how about embedding some custom HTML to the end of the post? Use shortcodes.

Time to dive in some action. To accomplish this fairly simple task, you have to edit functions.php (or create a plug-in file) to make the shortcodes work. Just follow the steps below to reveal the magic of shortcodes:

Create A Shortcode

Creating shortcodes is simple and easy. It just requires few lines of PHP codes to get started. Firstly, create a handler function and secondly turn the function into shortcode. Here is the procedure for creating a shortcode for the above said example (a shortcode for replacing [w] for WordPress in HTML editor).

  1. Open functons.php in the text editor of your choice. Create one if does not exist. Optionally you can also create a plug-in file as well.
  2. Add the following code in functions.php to create a function handler:
    
    function wp()
    {
    return 'WordPress'; //you can make this to return anything, even html
    }
    
  3. Add the following code to turn wp function into a shortcode:
    
    add_shortcode('w', 'wp');
    

    The add_shortcode function is provided by the Shortcode API to create shortcodes; which takes two parameters. Where first parameter is the name of the shortcode and the second parameter is the name of the function to be called.

Using Shortcode In Post Content

Now that the shortcode is created, you can easily use it in your post content whenever required. Be careful, the shortcode works in the HTML editor only, that’s too with a specific syntax. Type in [w] for replacing it with “WordPress” when the draft is saved.

Shortcode Examples (To Copy-Paste The ShortCodes)

The example stated above is good for beginners and but understates the usefulness and power of the shortcodes. Shortcodes are in fact very powerful and superficial feature of WordPress. You can use shortcodes to create beautiful download boxes, fetch posts from WordPress database, integrate Google Adsense ads or even for listing related posts. Here are few examples to justify the competence of WordPress shortcode (as against using plug-ins for the same task):

  1. Create “Subscribe To RSS” Shortcode

    Add the following code in functions.php:

    function subscribeRss() {
    return '<div class="rssbox"><a href="http://feeds.feedburner.com/wprecipes">Enjoyed this post? Subscribe to my RSS feeds!</a></div>';
    }

    add_shortcode(‘subscribe’, ‘subscribeRss’);
    Replace the feed URL with your own feed URL and add the following code in style.css to style the RSS box mentioned in above code:

    .rss-box{
    background:#F2F8F2;
    border:2px #D5E9D5 solid;
    font-weight:bold;
    padding:10px;
    }

    Usage: [subscribe]

  2. Integrate Google Adsense in post content

    Add the following code in functions.php:

    function showads() {
    return '<script type="text/javascript"><!--
    google_ad_client = "<insert publisher id here>";
    google_ad_slot = "<ad slot>";
    google_ad_width = 468;
    google_ad_height = 60;
    //-->
    </script>
    <script type="text/javascript"
    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
    </script>
    ';
    }
    add_shortcode('adsense', 'showads');

    Usage: [adsense]

  3. Create A Short URL For Twitter

    Add the following code in functions.php:

    function subzane_shorturl($atts) {
    extract(shortcode_atts(array(
    'url' => '',
    'name' => '',
    ), $atts));
    $request = 'http://u.nu/unu-api-simple?url=' . urlencode($url);
    $short_url = file_get_contents($request);
    if (substr($short_url, 0, 4) == 'http')    {
    $name = empty($name)?$short_url:$name;
    return '<a href="'.$short_url.'">'.$name.'</a>';
    } else {
    $name = empty($name)?$url:$name;
    return '<a href="'.$url.'">'.$name.'</a>';
    }
    }
    add_shortcode('shorturl', 'subzane_shorturl');
    

    Usage: [shorturl]

  4. Call A Widget With A Shortcode

    Add the following code in functions.php:

    function widget($atts) {
    global $wp_widget_factory;
    extract(shortcode_atts(array(
    'widget_name' => FALSE
    ), $atts));
    $widget_name = wp_specialchars($widget_name);
    if (!is_a($wp_widget_factory->widgets[$widget_name], 'WP_Widget')):
    $wp_class = 'WP_Widget_'.ucwords(strtolower($class));
    if (!is_a($wp_widget_factory->widgets[$wp_class], 'WP_Widget')):
    return '<p>'.sprintf(__("%s: Widget class not found. Make sure this widget exists and the class name is correct"),'<strong>'.$class.'</strong>').'</p>';
    else:
    $class = $wp_class;
    endif;
    endif;
    ob_start();
    the_widget($widget_name, $instance, array('widget_id'=>'arbitrary-instance-'.$id,
    'before_widget' => '',
    'after_widget' => '',
    'before_title' => '',
    'after_title' => ''
    ));
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
    }
    add_shortcode('widget','widget');

    Usage: [widget widget_name=”Your_Custom_Widget”]

    where “widget” is the name of the shortcode and widget_name is the parameter to be passed to the handler, to activate the required widget.

  5. Displaying Related Posts

    Add the following code in functions.php:

    function related_posts_shortcode( $atts ) {
    extract(shortcode_atts(array(
    'limit' => '5',
    ), $atts));
    global $wpdb, $post, $table_prefix;
    if ($post->ID) {
    $retval = '<ul>';
    // Get tags
    $tags = wp_get_post_tags($post->ID);
    $tagsarray = array();
    foreach ($tags as $tag) {
    $tagsarray[] = $tag->term_id;
    }
    $tagslist = implode(',', $tagsarray);
    // Do the query
    $q = "SELECT p.*, count(tr.object_id) as count
    FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id  = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID
    AND p.post_status = 'publish'
    AND p.post_date_gmt < NOW()
    GROUP BY tr.object_id
    ORDER BY count DESC, p.post_date_gmt DESC
    LIMIT $limit;";
    $related = $wpdb->get_results($q);
    if ( $related ) {
    foreach($related as $r) {
    $retval .= '<li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>';
    }
    } else {
    $retval .= '
    <li>No related posts found</li>';
    }
    $retval .= '</ul>';
    return $retval;
    }
    return;
    }
    add_shortcode('related_posts', 'related_posts_shortcode');

    Usage: [related_posts]

What’s your take on WordPress Shortcodes?

Divi WordPress Theme