WordPress development tutorials

Shortcodes are a great feature of WordPress, and many plugins include their own handy shortcodes. For example, WooCommerce includes several shortcodes. These can allow you to create “Buy Now” buttons, insert products into blog posts, display related products or featured products, and more.

While these shortcodes are really helpful, as are the shortcodes included by most plugins or extensions, it’s still very useful to create a WordPress shortcode for your own use.

For example, I use shortcodes over at Sell with WP to insert anchor links and link icons for my headers automatically. You can also create your own shortcodes to:

  • Insert content that you find yourself repeating, such as a refund / return policy.
  • Extend what’s displayed by a plugin (i.e., using WooCommerce shortcodes to show featured products)
  • Do something, like restrict blocks of content (some membership plugins do this, like MemberMouse)

The WordPress codex information on shortcodes makes a good guide to shortcodes, but let’s walk through creating a couple of simple shortcode types. You can use these or extend them to create a WordPress shortcode of your own. Remember to properly add this code to your site via a plugin or snippet with Code Snippets.

Create a WordPress Shortcode to insert content

Let’s create a shortcode that will insert our refund policy, which we can use on a product page, blog posts, or our refund policy page. This can be any content you’d like, including an image. Our shortcode will be able to accept any valid HTML.

While some shortcodes “open” and “close” with a structure like [my_shortcode]Some Content[/my_shortcode], we can also have a very simply shortcode that just inserts something with a structure [my_shortcode]. This is the kind of shortcode we’ll build first.

First, let’s write our refund policy. We’ll make it super simple:

Sorry, we’re not able to offer refunds on this product since it’s customized! Please be sure spelling and options are correct before ordering.

Okay, now let’s create a shortcode called [sv_refund_policy] that will insert this text when used. Note that I’ve added a prefix for “SkyVerge” – it’s a good idea to prefix your shortcodes and functions to avoid any conflicts in the future with themes or plugins. There are a couple of basic pieces every shortcode should have:

  • A handler function. This function will create the functionality of the shortcode – essentially, this function will tell WordPress what the shortcode should do.
  • A shortcode name. We’ll use this with the WordPress add_shortcode() function to create the shortcode. The name for this example will be sv_refund_policy.

Let’s write our handler function to echo our refund policy:

[code lang=”php”] function sv_create_refund_policy_shortcode( $atts ) {

// Buffer our contents
ob_start();

return ‘Sorry, we\’re not able to offer refunds on this product since it\’s customized! Please be sure spelling and options are correct before ordering.’;

// Return buffered contents
return ob_get_clean();

}
[/code]

There are a few things to note. First, I pass in $atts for attributes to the handler function. However, this shortcode won’t have any attributes, so we don’t have to set any.

I also didn’t have to buffer the contents of my HTML by wrapping it in the ob_start() and ob_get_clean(); functions, but did so here for an example. If you output HTML to the page with a template tag or another function, you’ll want to include this (I do it out of habit anyway). Without buffering the contents of the shortcode, your HTML will just display at the top of your page since your shortcode will be expanded before your content. This is also needed if you echo something on the page rather than returning it.

Also note that I’ve used a backslash in front of my apostrophes to escape them. This is necessary as a PHP indicator that I’m not closing the return part, but rather this is part of what I want echoed.

Now, let’s use this function to register our new shortcode. Add the shortcode name first, then the handler function name to register it.

[code lang=”php”] add_shortcode( ‘sv_refund_policy’, ‘sv_create_refund_policy_shortcode’ );
[/code]

That’s it! Put these two tiny bits of code together into a snippet or plugin. Now you can use [sv_refund_policy] anywhere on your site, and it will display your refund policy instead.

We have lots of examples of these simple shortcodes in our post on Advanced WooCommerce Social Login uses.

Create a WordPress Shortcode to accept content

Now let’s talk about the type of shortcode we mentioned earlier – the kind that opens and closes like this:

[my_shortcode]Some Content[/my_shortcode]

This kind of shortcode will require another variable passed into our handler function. We’ll have to pass in the $content variable. You can set a default for the content by using $content = default, but most likely you’ll see this without a default set: $content = null.

Let’s create a shortcode that will display a message to logged-in users. This could be used to display a coupon code to registered customers if they’re logged in. We’ll also display a generic message to non-logged in users.

Our shortcode content will be the message, and our handler function will first check to see if the user is logged-in before displaying this content using a conditional tag (we’ve explained their use in this tutorial).

We’ll create an [sv_member_message] shortcode that displays a message.

[code lang=”php”] function sv_member_message_shortcode( $atts, $content = null ) {

if( is_user_logged_in() ) {
return $content;
} else {
return ‘<em>Sorry, you must be a registered customer to view this!</em><br />Log into your account to view the code.’;
}
}
add_shortcode( ‘sv_member_message’, ‘sv_member_message_shortcode’);
[/code]

Now we can use this shortcode in a post to provide content only to our logged-in, registered customers. Let’s give them a bonus coupon at the end of the post by adding our content wrapped in the shortcode:

Log into see the coupon code:
[sv_member_message]The coupon code is: <code>Halloween20</code>[/sv_member_message]

If the customer is logged in, s/he will see our message:

Content Restriction Shortcode

Customer Logged In

If not, then the content of the shortcode will not be displayed. Instead, we’ll display our generic rejection message and ask customers to log in for the code:

Content Restriction Shortcode

Customer Not Logged In

Go nuts with your holiday promotions! You can provide these coupons to customers only in your blog or on pages on your site.

Create a WordPress Shortcode with content and arguments

Now let’s create a shortcode that requires arguments. These can be passed into the shortcode along with content, and can act as “options” for the shortcode. The structure will look something like this:

[my_shortcode arg1="value1" arg2="value2"]Some Content[/my_shortcode]

Let’s create a button for which the content will be the button text, and we’ll use arguments for the button URL and target (whether it opens in the same window or a new one). When we create our handler function, we’ll still include the $content, but we’ll need to change the $atts into an array of options using the shortcode_atts() function.

Let’s create array $a of our attributes, and this array will include the URL and target (use all lowercase names). You can set the default value for each, which will be used if they’re not set within the shortcode.

[code lang=”php”] function sv_add_button_shortcode( $atts, $content = null ) {

$a = shortcode_atts( array(
‘url’ => ‘#’,
‘target’ => ‘_self’,
), $atts );

return ‘<a href="’. esc_attr($a[‘url’]) .’" target="’. esc_attr($a[‘target’]) .’" class="sv-button">’. $content .'</a>’;

}
add_shortcode( ‘sv_button’, ‘sv_add_button_shortcode’ );
[/code]

Notice that I add default values for each of these, and then I reference the items in the array in the HTML that I return using esc_attr($a['url']). This will access the value for the 'url' key and insert it. The same can be said of the “target” portion. I’ve also added a class for this button, and added styling to my CSS stylesheet to turn it into a button rather than just a link.

Now I can add it to a page, and enter values for my shortcode attributes:

[sv_button url="https://www.skyverge.com/" target="_blank"]My button[/sv_button]

This will output my button on the page, along with the styling I’ve added for the sv-button class in my CSS stylesheet:

Sample Button Shortcode

The button will link to my URL, and will open in a new window since I’ve set the target as _blank.

Create a WordPress Shortcode: Summary

You can create a WordPress shortcode to insert content, extend a plugin’s functionality, or execute a task when used in WordPress. While these are beginner examples, shortcodes can be used for more complex functions. However, they’re easy enough to add that you can start creating your own for your WordPress site.

Published by Beka Rice

Beka leads product direction for SkyVerge, focusing on new features for our plugins and Jilt. She spends a lot of time on research and interviews, but likes to write so she has an excuse to spend more time jamming out to anything from The Clash to Lady Gaga.

10 Comments

  1. Great Beka! Really useful post!

  2. […] your own shortcodes to your site can be immensely useful – here’s a tutorial on how to create WordPress shortcodes from […]

  3. Excellent tutorial Beka! I’m looking to build a pricing table shortcode exactly like Avada theme has. Could you please help me in that?

    Regards,
    Deven

  4. Hi Beka
    Great little tutorial – I’ve used it to demonstrate to some of my WordPress students and it works a treat!
    But I have a curly one for you:
    I want to extend woocommerce’s product categories shortcode:
    I’m trying to use the WooCommerce shortcode to display filtered product categories.
    Either: show products that are in BOTH category X and category Y (preferable)
    Or: Show products that are in Category X but NOT category Y.
    The standard shortcode is [product_category category=”X”].
    I’d love to be able to do something like this (dodgy code but you’ll get the idea)

    [product_category category=”X+Y”] (products that are in BOTH categories)
    or
    [product_category category=”X-Y”] (products that are in X but not Y categories)

    Operators could be && or || or == or != etc – whatever works best.
    Any ideas?
    Cheers
    from Melbourne Oz

    • Hey John, you’d be better off creating your own new shortcode instead of trying to modify the default WooCommerce one. The logic around querying those products is definitely higher level stuff, I’d recommend creating a shortcode that does your own taxonomy query, perhaps using multiple attributes like [custom_product_cat category="slug1, slug2" relation="and" not_in="slug3"] instead of trying to parse a math-like string.

  5. Hi Beka,

    This is very useful. I am fairly new to WP and I am trying to create a shortcode to identify a user who is NOT a member of a membership plan (in WooCommerce) and restrict content. I have been successful in creating shortcodes for logged in and logged out users, but I would like to know how to reference a Woocommerce membership in the shortcode function. So instead of this:

    if( is_user_logged_in() ) { ... }

    Something like this:

    if( !is_user_member("basic-membership") ) { ... }

    I am trying to find the right way to reference a membership (I just made up the ‘is-user-member’, but I assume there is something similar. Can you give me a hint for creating such a shortcode?

    PS: WooCommerce Memberships does have a shortcode for restricting content based on membership, e.g. [wcm_restrict plans=”basic-membership”]. I just want to do the opposite.

    Leon

Hmm, looks like this article is over 2 years old! Its content may be outdated, so comments are now closed.