How to create a shortcode in WordPress with examples
WordPress shortcodes are a useful feature that allows you to do many outstanding things on your website with minimal effort. Putting interactive components or complicated page layouts is as simple as inserting a single line of code with shortcodes. In fact, shortcodes do away with the necessity for lengthy scripts. With their help, you can easily create dynamic content even if you have little to no programming abilities. In this post, Arrowtheme will instruct you how to create a shortcode in wordpress with specific examples. Then, explore with us right now!
What are shortcodes in WordPress?
Shortcodes are code shortcuts in WordPress that allow you to add dynamic content to posts, pages, and sidebar widgets. Typically, it is written in square brackets as: [myshortcode]
For more details, WordPress monitors all content to ensure that malicious code is not inserted into the database via posts and pages. Simply speaking, this means that you can include basic HTML in your postings but not PHP code.
Moreover, the shortcode API is useful if you want to use custom code to display related posts, banner advertisements, contact forms, galleries, and other content inside your posts. Essentially, it allows developers to place their code inside a function and then register that function as a shortcode with WordPress. Hence, it enables consumers to utilize it without needing to know any coding. Finally, WordPress will run the code associated with the shortcode once it has been found.
How to create a shortcode in WordPress with examples?
#1. WordPress shortcode using [current_year]
Let’s make a [current_year] shortcode that displays the current year on your WordPress website. To put it plainly, if you are adding content to your website that needs to be updated every year, this shortcode will come in handy. Specifically, it will provide a copyright notice at the footer of your website.
Moreover, in order to create a shortcode in WordPress, you can utilize a simple plugin. There are lots of WordPress plugins for you to do this, such as: WPForms for contact forms, OptinMonster for email marketing forms, WP Call Button for putting a call to action button and so much more. What’s more, you can obtain the same effects by including it in your theme’s functions.php file.
To begin, you have to create a plugin by generating a new folder in your /wp-content/plugins/ directory.
Then, the next thing you must do is create a PHP file with the same name in the salcodes plugin directory. Don’t forget to add the following header to your plugin’s file as soon as you finish it. Finally, you must save the file, then activate the plugin from your WordPress panel.
Let’s now create a shortcode in WordPress and its handler method to the database. Following that, you must add the code as below to your plugin’s file to accomplish this:
/**
* [current_year] returns the Current Year as a 4-digit string.
* @return string Current Year
*/
add_shortcode( ‘current_year’, ‘salcodes_year’ );
function salcodes_init(){
function salcodes_year() {
return getdate()[‘year’];
}
}
add_action(‘init’, ‘salcodes_init’);
/** Always end your PHP files with this closing tag */
?>
@return tag
The type of output produced is defined by the @return tag in the PHP remark. It’s followed by a brief explanation of the subject.
current_year
The shortcode current_year refers to the tag or name. This specifies the self-closing tag you must use in your text, which is [current_year] in this example.
salcodes_year
The output string will be returned by the shortcode handler function salcodes_year. In the next lines, we will define this callback function. You don’t need to give any variable values like $attributes, $content, or $tag because we are making a simple self-closing shortcode.
salcodes_init
The wrapper function salcodes_init is hooked to ‘init’ to ensure that the shortcode is registered and runs only after WordPress has finished loading. In fact, this is achievable thanks to WordPress’s inbuilt add_action() function.
getdate()
This is a PHP function that returns an array containing the current timestamp’s date information. The current year’s value is stored in the year key. Besides, the current year is returned by getdate()[‘year’].
Most importantly, you must save the plugin file. It’s now time to see if the shortcode actually works. Best of all, the shortcode can be used anywhere on your website including page, post, sidebar widget, etc. In this case, we are going to put it in the Text widget on the sidebar of our website.
As you can see, there are no $attributes or $content variables connected with the shortcode you just created. If you want, the following examples will show you how to use them.
#2. Create a shortcode in WordPress for a CTA button
In this example, let’s make a CTA Button shortcode that can be customized. With the shortcode properties, users are able to change the size and color of the CTA Button. Besides, because the final product is a button element, HTML elements like href, id, class, target, and label may be used to easily alter it. In addition, since the id and class properties are both basic CSS selectors, you can utilize them to style the button. Then, let’s see the following code:
/**
* [cta_button] returns the HTML code for a CTA Button.
* @return string Button HTML Code
*/
add_shortcode( ‘cta_button’, ‘salcodes_cta’ );
function salcodes_cta( $atts ) {
$a = shortcode_atts( array(
‘link’ => ‘#’,
‘id’ => ‘salcodes’,
‘color’ => ‘blue’,
‘size’ => ”,
‘label’ => ‘Button’,
‘target’ => ‘_self’
), $atts );
$output = ‘<p><a href=”‘ . esc_url( $a[‘link’] ) . ‘” id=”‘ . esc_attr( $a[‘id’] ) . ‘” class=”button ‘ . esc_attr( $a[‘color’] ) . ‘ ‘ . esc_attr( $a[‘size’] ) . ‘” target=”‘ . esc_attr($a[‘target’]) . ‘”>’ . esc_attr( $a[‘label’] ) . ‘</a></p>’;
return $output;
}
As you can see, there are lots to unpack here. Let’s refer to the meaning of each now:
add_shortcode()
This function works like the above example we mentioned.
shortcode_atts()
This is a WordPress function that combines known and user-supplied shortcode attributes. When necessary, it fills in default values. Furthermore, the end output will be an array with every key from the known attributes combined with values from user-defined shortcode attributes.
variable ($a)
You can define a variable ($a) and assign it to the array given by shortcode_atts() inside the shortcode handler method. Besides, you use the syntax: ‘attribute’ => ‘default-value’ to set the default values for the attributes. For example, in the above code, you can use the syntax ‘label’ => ‘Button’ to set the default value of attribute label to Button.
$a[‘attribute’]
Using the PHP syntax for arrays, you are able to extract the values for each attribute key: $a[‘attribute’].
$output
The HTML code of the button element (<a> tag with ‘button’ class) is stored in the $output variable. Then, the function finally returns the string.
After that, you can utilize the home_url() WordPress function to make the default link your site’s homepage URL. Now, let’s examine what happens if we just use the shortcode without any characteristics.
Additionally, the ([[cta_button]]) is called the escaping shortcode. They allow you to display any registered shortcode in your website as plain text.
What’s more, the shortcode allows users to change the button’s size and color. Although we already defined their default settings in the handler method, we still need to add the stylesheet to the list of available resources by registering and enqueuing it. More crucially, all of the classes defined in the shortcode should be present in this CSS.
Alternatively, these classes can also be specified in your theme’s global stylesheet. However, it’s best to load them separately. This ensures that these classes will load alongside the shortcode even if your WordPress theme is changed or updated.
/** Enqueuing the Stylesheet for the CTA Button */
function salcodes_enqueue_scripts() {
global $post;
if( is_a( $post, ‘WP_Post’ ) && has_shortcode( $post->post_content, ‘cta_button’) ) {
wp_register_style( ‘salcodes-stylesheet’, plugin_dir_url( __FILE__ ) . ‘css/style.css’ );
wp_enqueue_style( ‘salcodes-stylesheet’ );
}
}
add_action( ‘wp_enqueue_scripts’, ‘salcodes_enqueue_scripts’);
Furthermore, the salcodes_enqueue_scripts() function creates the global variable $post and then checks two conditions:
is_a()
The first is is_a() that determines whether $post is a WP_Post object instance. It refers to all of WordPress’s post types.
has_shortcode()
This condition determines whether the [cta_button] shortcode is present in the post text.
In short, the style.css stylesheet present in the CSS folder is registered and enqueued if both requirements are true. The plugin_dir_url($file) method makes obtaining the URL of a plugin’s directory a breeze.
In this example, we won’t show you the CSS code right now, but you can find it in the source code at the bottom of this page. Finally, you can put the [cta_button] shortcode to the test by including it in the content of the post:
Now, let’s take a look at the following image to see how the CTA Button appears on the frontend:
Moreover, you can extend the functionality of your CTA Button shortcode now that you know how to build custom properties and include styles. You can, for example, allow your users to add animations, hover effects, and a variety of additional button designs.
#3. Create a shortcode in WordPress by using $content
Coming to the last example you should know in this topic is to use $content. For more details, you must create a [boxed] enclosing shortcode that displays any material between tags in a box with colorful titles.
To begin, you must define the shortcode’s handler function and register it.
/**
* [boxed] returns the HTML code for a content box with colored titles.
* @return string HTML code for boxed content
*/
add_shortcode( ‘boxed’, ‘salcodes_boxed’ );
function salcodes_boxed( $atts, $content = null, $tag = ” ) {
$a = shortcode_atts( array(
‘title’ => ‘Title’,
‘title_color’ => ‘white’,
‘color’ => ‘blue’,
), $atts );
$output = ‘<div class=”salcodes-boxed” style=”border:2px solid ‘ . esc_attr( $a[‘color’] ) . ‘;”>’.'<div class=”salcodes-boxed-title” style=”background-color:’ . esc_attr( $a[‘color’] ) . ‘;”><h3 style=”color:’ . esc_attr( $a[‘title_color’] ) . ‘;”>’ . esc_attr( $a[‘title’] ) . ‘</h3></div>’.'<div class=”salcodes-boxed-content”><p>’ . esc_attr( $content ) . ‘</p></div>’.'</div>’;
return $output;
}
- $content = null
The shortcode is registered as an enclosing type when $content = null is used. Within your handler function, you can use the $content variable to alter the output as needed.
- $tag = ”
Although defining the $tag variable of the shortcode isn’t required, you should still do so.
In this case, you can use inline CSS styles to change the content. As with the previous shortcode example, styles for any classes used within the shortcode are registered and enqueued. However, because two shortcodes share the same stylesheet, you must load it if either of them is utilized. Now, you should make some changes to the salcodes_enqueue_scripts() function:
/** Enqueuing the Stylesheet for Salcodes */
function salcodes_enqueue_scripts() {
global $post;
$has_shortcode = has_shortcode( $post->post_content, ‘cta_button’ ) || has_shortcode( $post->post_content, ‘boxed’ );
if( is_a( $post, ‘WP_Post’ ) && $has_shortcode ) {
wp_register_style( ‘salcodes-stylesheet’, plugin_dir_url( __FILE__ ) . ‘css/style.css’ );
wp_enqueue_style( ‘salcodes-stylesheet’ );
}
}
add_action( ‘wp_enqueue_scripts’, ‘salcodes_enqueue_scripts’);
- $has_shortcode
This is a user-defined variable that determines whether one or both of the shortcodes are present on the page/post. Plus, this is made feasible using the || (OR operator).
Then, let’s put our [boxed] shortcode to the test.
The following screenshot is the result:
What are advantages and disadvantages of shortcode WordPress?
Advantages of shortcode wordpress
- First and foremost, shortcodes make it easier to add sophisticated features to WordPress sites. To put it plainly, a single line of code can be used to add practically anything.
- Secondly, shortcodes wordpress help to speed up the development process. In fact, they will get rid of the necessity to develop complicated programs every time you wish to add a new feature.
- Thirdly, they work well with plugins. Best of all, they will remain valid and work as they did previously, even if you upgrade WordPress or change/update your theme.
- What’s more, they are easier to utilize across numerous WordPress websites when they are packaged inside plugins. Therefore, having all of your custom shortcodes ready to go is a lifesaver if you’re a developer who manages multiple sites.
- Furthermore, because shortcodes accept attributes, users can change the behavior of the same shortcode by simply changing its attribute settings.
Disadvantages of shortcode wordpress
- First of all, wordpress shortcodes aren’t intuitive for end users to utilize, especially when there are a lot of them on a website. In reality, they’re more suited for developers in these situations.
- Besides, if only glancing at a shortcode, it’s difficult to discern what it performs. For this reason, the WordPress core team has dubbed them “mystery meat embed codes”.
- Additionally, if you alter your theme, shortcodes that came with it will cease working.
- In terms of syntax, shortcodes are unclear.
- In addition, due to conflicting tags or interoperability difficulties, shortcodes might cause HTML to fail. Plus, seeing them on a website’s interface is never a good thing.
- In particular, shortcodes can increase the amount of work your server has to do. This load increases as the number of shortcodes on your page/posts grows. This is the reason why your website may slow down if you use too many shortcodes.
Shortcode in WordPress vs Gutenberg Blocks
After Gutenberg was introduced, shortcodes in WordPress became less desirable. Instead of dealing with shortcode markups, users now are able to add blocks directly from the editing interface, no matter how simple they are. In case you want to utilize shortcodes, Gutenberg includes a dedicated block for that purpose. Now, shortcodes have been replaced by Blocks. This is the reason why all of the most commonly used shortcodes have been transformed to blocks. Now, a lot of WordPress developers have switched to only using the block editor for their businesses and services.
However, this does not imply that shortcodes are removed. The WordPress core team strives to make many changes to the block editor, but shortcodes are here to stay for the time being.
Wrapping up
To sum up, shortcodes in wordpress make it simple to add complicated functionality to your WordPress website. Simply speaking, they provide users with simple-to-type tags that they may utilize without having to learn complex codes. All in all, this article brings you a comprehensive guide to create a shortcode in WordPress with some simple steps.
What’s more, Arrowtheme also offers WordPress Website Packages that can solve every issue for you. Our wordpress packages include everything you definitely need to get your online business up and operating quickly. Best of all, if you use our Shopify services during this time, you will earn a spectacular 30% discount. Please use our CONTACT FORM to connect with us for further information. Then we will contact you as soon as possible to provide you with the best answer.