Home / My WordPress / WordPress (WordPress Shortcuts)

WordPress (WordPress Shortcuts)

Introduced in WordPress version 2.5, shortcodes are powerful but still little-known feature of WordPress. Imagine that you can just type “adsense” to display an AdSense ad or “post_count” to instantly know the number of posts in your blog.

Шорткоды Вордпресс

WordPress shortcuts can make this and more possible, and can definitely make your blogger life easier. In this article, we will show you how to create and use shortcodes, as well as examples of ready-made shortcodes that will significantly increase your blogger experience.

What are shortcode(shortcode)?

To use shortcodes is very easy. To do this, create a new post(or open an existing post for editing), switch the editor to HTML mode and enter a shortcode in square brackets, like this:


Also with short codes it is possible to use attributes. Then they will look like this:

[showcase id="5"]

Shortcode also allows you to embed content:

[url href="http://www.smashingmagazine.com"]Smashing Magazine[/url]

The shortcuts are driven by a set of features introduced in WordPress 2.5 called the Shortcode API. When a post is saved, its content parses and the Shortcode API automatically transforms the shortcode to execute the function assigned to it.

Creating a simple shortcode

Shortcode is very easy to create. If you know how to write a simple Php function, you already know how to create a WordPress shortcode. To begin, let’s create the famous message “Hello world»


    1. Open the functions file.php of your theme. If it’s not there, create it.
      First, we need to create a function to output the string “Hello world”.
    2. Paste the following code into your functions file.php:
      function hello() {
          return 'Привет, мир!';
    3. Now we have a function, we have to turn it into a shortcode. This is very easy to do thanks to the add_shortcode () function. Paste this line after our hello () function, then save and close the functions file.php:
      add_shortcode('hw', 'hello');

      The first parameter is the shortcode name, and the second parameter is the function name.

    4. Now that the shortcode is created, we can use it in posts and pages. To do this, simply switch to HTML mode and enter the following:

      That’s it! Of course, this is a very simple shortcode, but this is a good example of how easy it is to create.

      Creating advanced shortcode

      As mentioned, shortcuts can be used with attributes that are very useful. In this example, we’ll show you how to create a shortcode to output the URL, just as you did with BBCode on forums like VBulletin and PHPBB.


  1. Open your functions file.php. Insert the following function into it:
    function myUrl($atts, $content = null) {
    		"href" => 'http://'
    	), $atts));
    	return '<a href="'.$href.'">'.$content.'</a>';
  2. Now let’s convert the function into a shortcode:
    add_shortcode("url", "myUrl");
  3. [url href="http://www.vverx.com"]Вверх_ком, настройка WordPreThe shortcode is created. You can use it in posts and pages about the way:ss[/url]

    When you save the post, the shortcode displays a link entitled “Warcom, setting up WordPress” and leading to the http://www.vverx.com.

Explanation of the code. To work properly, the functions of our shortcode should be handled with two parameters: $attr and $content. $attribute(s) is a shortcode attribute. In this example, the attribute is called href and contains a link to the URL. $content is the content of the shortcode, embedded between the domain and sub-directory(i.e. between “www.example.com” and “/subdirectory”). As you can see in the code we gave $content and $atts default values.

Шорткоды Вордпресс2

Now we know how to create and use shortcodes, let’s check out a few ready-to-use shortcodes!

1. Shortcode send to Twitter

Purpose. Display a link to send a post to Twitter.

This shortcode is easy to create. Paste the following code into the functions file.php of your theme:

function twitt() {

  return '<div id="twitit"><a href="http://twitter.com/home?status=Currently reading '.get_permalink($post->ID).'" title="Кликни и отправь этот пост в твиттер!" target="_blank">Отправить в твиттер</a></div>';

add_shortcode('twitter', 'twitt');

To use it, simply switch to HTML mode and type twitter in square brackets.
And the link Send to Twitter will appear where you left the shortcode.

2. Create shortcode “Subscribe to RSS»

You already know that a very good way to increase the number of RSS subscribers is to show a well-designed message that says something like “Sign up for an RSS feed.” But again, we do not really need to specifically change the code of our topic and lose control over where this message appears. In this reception we will create a shortcode “Subscribe to RSS”. Show in some places, in other not show, in governing and on pages, at the top and the bottom the principal content, to decide you.

As before, we create a function and then translate it into a shortcode. This code should be in your functions file.php. Don’t forget to change the feed URL in the example to your own!

function subscribeRss() {

    return '<div><a href="http://feeds.feedburner.com/vverxcom">Понравился пост? Подпишись на мой RSS фид!</a></div>';

add_shortcode('subscribe', 'subscribeRss');

Pastiche. You may have noticed the rss-box class that is added to the div containing the reference. It will allow you to stylize the message to taste. Here is an example of some CSS style that you can apply on your message. Just paste it into the style file.css of your theme:

  border:2px #D5E9D5 solid;

3. Insert Google AdSense anywhere you want

Many bloggers use Google AdSense. Very simple to insert the AdSense code in the theme file, such as a sidebar.php. But successful online marketers know that people click more often on ads that are embedded in content.

To embed AdSense anywhere in your post or page, create a shortcode:


  1. Open the functions file.php of your theme and paste following code. Don’t forget to replace the JavaScript code with their own AdSense code!
    function showads() {
        return '<div id="adsense"><script type="text/javascript"><!--
    google_ad_client = "pub-8683604175367491";
    /* 468x60, создано 05.02.09 */
    google_ad_slot = "5183274352";
    google_ad_width = 468;
    google_ad_height = 60;
    <script type="text/javascript"
    add_shortcode('adsense', 'showads');
  2. Saving changes to functions.php, you can use the following shortcode to display AdSense anywhere in your posts and pages:

    Note that Our AdSense code is wrapped in div with id=”adsense”, we can add style to it in style file.css.

Explanation of the code. The top code is used simply to display AdSense ads. When the shortcode is inserted into the post, it returns AdSense ad. It’s pretty simple, but agree really saves time!

4. Embed RSS feed

Let’s put an RSS feed right into our posts and pages. ((This trick is buggy with the Russian coding, if someone knows why, please leave feedback in the comments)

As usual, to make this trick work, just copy the following code into the function file.php of your theme.

//This file is needed to be able to use the wp_rss() function.


function readRss($atts) {
	"feed" => 'http://',
      "num" => '1',
    ), $atts));

    return wp_rss($feed, $num);

add_shortcode('rss', 'readRss');

To use the shortcode, enter:

[rss feed="http://feeds.feedburner.com/wprecipes" num="5"]

The feed attribute is the URL that is embedded in the view, and num is the number of posts to output.

Take the posts from WordPress database with a shortcode

Ever wanted to call up a list of related posts directly in WordPress editor? Of course, the plugin “Simple Tags” or “Related posts” can show related posts, but with a shortcode you can easily get a list of any number of posts from a particular category.

Paste this code into your functions file.php.

function sc_liste($atts, $content = null) {

                "num" => '5',
                "cat" => ''
        ), $atts));
        global $post;
        $myposts = get_posts('numberposts='.$num.'&order=DESC&orderby=post_date&category='.$cat);
        foreach($myposts as $post) :
             $retour.='<li><a href="'.get_permalink().'">'.the_title("","",false).'</a></li>';
        $retour.='</ul> ';
        return $retour;
add_shortcode("list", "sc_liste");

To use put the following into the WordPress editor, in HTML mode:

[liste num="3" cat="1"]

This will display a list of three posts from category ID 1.

Explanation of the code. After extracting the arguments and creating the $posts global variable, the sc_lite() function uses the get_posts() function with the numberposts, order, orderby, and category parameters to get the X most similar posts from the Y category. After that, the posts are embedded in the HTML list and displayed on the screen.

6. Call a picture of the last post

In WordPress is quite simple to manipulate images. But why not simplify it even more? Let’s look at a more complex shortcode, which automatically causes the last picture attached to the post.

Open the functions file.php and paste the following code:

function sc_postimage($atts, $content = null) {

		"size" => 'thumbnail',
		"float" => 'none'
	), $atts));
	$images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );
	foreach( $images as $imageID => $imagePost )
	$fullimage = wp_get_attachment_image($imageID, $size, false);
	$imagedata = wp_get_attachment_image_src($imageID, $size, false);
	$width = ($imagedata[1]+2);
	$height = ($imagedata[2]+2);
	return '<div style="width: '.$width.'px; height: '.$height.'px; float: '.$float.';">'.$fullimage.'</div>';
add_shortcode("postimage", "sc_postimage");

To use this shortcode, just type the following line in the editor in HTML mode

[postimage size="" float="left"]

Explanation of the code. Function sc_postimage() first checks the attributes of the shortcode. Then it takes a picture using the following functions WordPress get_children (), wp_get_attachment_image () and wp_get_attachment_image_src (). After that, the picture is returned, embedded in the content of the post.

Add shortcodes in the widgets sidebar

Even if you liked this article, you might be a little unhappy, because by default WordPress does not allow you to insert the shortcode in the side column widgets. Fortunately, there is a little trick that increases the functionality of WordPress and allows you to use the shortcuts in the side column widgets.

A little more code to insert into the functions file.php:

add_filter(‘widget_text’, ‘do_shortcode’);

That’s all you need.

Explanation of the code. What we’ve done is pretty simple: we’ve added a filter to the widget_test () function to execute the do_shortcode () function, which uses the API to execute the shortcode. Therefore, the shortcuts are now included in the side column widgets.

Leave a Reply

Your email address will not be published. Required fields are marked *


Если вы хотите получать уведомления на свой E-mail о появлении новых статей, то рекомендуем вам чуть ниже ввести свой электронный почтовый адрес.