Skip to content

Shortcodes in WP: Your Powerful Ally

Alejandro Frades
Shortcodes en WP: Tu Poderoso Aliado

Shortcodes, or abbreviated codes, have become an essential tool in the WordPress ecosystem. They allow you to add features or content in various areas of our site in a simple way. In this article, we will cover everything you need to know to use and create a shortcode on your own site.

Unraveling the Shortcode in WordPress

A shortcode in WordPress is an abbreviated code that allows users to execute specific functions easily. This feature is especially useful when we need to add functionalities that would normally require complex code or HTML.

WordPress Default Shortcodes

  1. [ caption ]: Adds a caption to images.
  2. [ gallery ]: Displays images in a gallery format.
  3. [ audio ]: Incorporates audio files into posts or pages.
  4. [ video ]: Embeds video files into your content.
  5. [ embed ]: Controls the embedding of content from other sites.
  6. [ playlist ]: Displays multiple audio or video files in a playlist format.
  7. [ wp_caption ]: Similar to [ caption ], it’s an earlier version.

It’s important to mention that some of these shortcodes have additional attributes and options that you can use to customize their behavior and appearance. While these summaries give you a general idea, it’s always advisable to consult the official WordPress documentation for deeper details and updates. I hope this information is useful to you!

The 2 Types of Shortcodes

In the WordPress ecosystem, we mainly find two types of shortcodes: standalone shortcodes and shortcodes that wrap content. Let’s detail each of them:

  • Standalone Shortcodes: These are the simplest and are represented by a single set of brackets. They don’t “wrap” any content and usually insert a specific element where they are placed. For example, the shortcode to display the current date would be something like [current_date].
  • Shortcodes that Wrap Content: These shortcodes work in pairs and “wrap” a content block, affecting how that content is displayed. A good example would be a shortcode to change the text color. It would look like this: [color text="red"]This is red text[/color].

The choice between the two will depend on the functionality you seek to implement on your website. The important thing is to know that both exist and offer flexibility to customize and enhance the functionality of your WordPress site.

Ways to Implement a Shortcode

Using WordPress Plugins

One of the easiest ways to add shortcodes is through specialized plugins. One of the most popular is Shortcodes Ultimate, which offers a wide range of predefined shortcodes. Simply install the plugin from your WordPress hosting, and it will be ready to use.

Manually Creating Shortcodes

If you prefer a customized solution, you can add your shortcode manually. To do this, you need to edit the functions file in your theme, specifically the functions.php. It’s essential to ensure you have a backup and are hosted on reliable VPS servers before making direct changes.

Example of Manually Created Shortcodes:

Shortcode to Display the Current Year

By adding a few simple lines of code to the functions.php, you can create a shortcode to display the current year, ideal for copyright in the footer.


    function current_year_shortcode() {
        return date("Y");
    }
    add_shortcode('current_year', 'current_year_shortcode');
    

Shortcode to insert a call to action (CTA) button:


function cta_button_shortcode($atts) {
    $a = shortcode_atts( array(
        'text' => 'Click here',
        'url'   => '#',
        'class' => 'btn-cta'
    ), $atts );
bash
Copy code
return '<a href="' . esc_url($a['url']) . '" class="' . esc_attr($a['class']) . '">' . esc_html($a['text']) . '</a>';
}
add_shortcode('cta_button', 'cta_button_shortcode');

Use this shortcode: [cta_button text=”Buy now” url=”https://mywebsite.com/buy” class=”btn-buy”]

Shortcode to display an email marketing subscription form


function email_form_shortcode() {
    return '<form action="/subscribe" method="post">
        <label for="email">Subscribe to our newsletter:</label>
        <input type="email" id="email" name="email" placeholder="Your email">
        <input type="submit" value="Subscribe">
    </form>';
}
add_shortcode('email_form', 'email_form_shortcode');

Use this shortcode: `[email_form]`

Shortcode to display a map:


function map_shortcode($atts) {
    $a = shortcode_atts( array(
        'url'   => 'https://www.google.com/maps/embed?pb=MAP_URL',
        'width' => '600',
        'height'  => '450'
    ), $atts );
css
Copy code
return '<iframe width="' . esc_attr($a['width']) . '" height="' . esc_attr($a['height']) . '" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' . esc_url($a['url']) . '"></iframe>';
}
add_shortcode('display_map', 'map_shortcode');

Use this shortcode: [display_map url=”MAP_URL” width=”800″ height=”600″]

Shortcode to display bold and italic at the same time in a word

function my_custom_shortcode( $atts, $content = null ) { return '' . $content . ''; } add_shortcode('bolditalic', 'my_custom_shortcode');

Once you have added this code, you can use the shortcode in your posts or pages as follows: [bolditalic]Your text here[/bolditalic]

Visitor Counter Shortcode

Creating a shortcode for a Visitor Counter involves not only creating the shortcode itself but also the logic to count and store visits. Here’s a basic method to create this:
function visitor_counter_shortcode() { if(isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views']+ 1; else $_SESSION['views'] = 1; return "views = ".$_SESSION['views']; } add_shortcode('visitor_counter', 'visitor_counter_shortcode');

Usage:

To display the counter, you can use [visitor_counter] wherever you want on your website. Note that this method uses PHP sessions, and there may be more efficient ways to store and retrieve these counts, especially for larger websites.

Conclusion

Shortcodes are a powerful tool for any WordPress site owner. Whether you choose to use plugins or prefer the manual route, the possibilities are endless. They allow you to expand the capabilities of your website in a way that’s user-friendly and efficient. Remember always to backup your site before making any changes, especially when modifying core files. Happy coding!

Note: This method is basic and not optimal for sites with high traffic or caching environments, as it may not register all visits correctly in such scenarios. For large or professional sites, it is recommended to use dedicated plugins or more advanced solutions.

Shortcode for Restricted Content

Here I present an example of how to create a shortcode to restrict content only for registered users. If a user is not registered, a message will be displayed indicating that they must log in to see the content.

function restricted_content_shortcode( $atts, $content = null ) { if ( is_user_logged_in() ) { return $content; } else { return '<p>You must <a href="' . wp_login_url() . '">log in</a> to view this content.</p>'; } } add_shortcode('restricted_content', 'restricted_content_shortcode');

With this shortcode, simply wrap the content you want to restrict within the tags [restricted_content] and [/restricted_content]. For example:
[restricted_content] This is content only for registered users. [/restricted_content]

Users who are not registered or who have not logged in will see a message telling them they must log in to view the content. On the other hand, users who have logged in will be able to see the content normally.

Add the provided code to your theme’s functions.php file (or, ideally, in a child theme or a custom plugin). Always remember to backup before making changes to files and, if possible, test in a staging environment before applying to the production site.

Adding Publication and Update Date of an Article


function dates_shortcode() {
    global $post;
bash
Copy code
$publication_date = get_the_date( 'd/m/Y', $post->ID );
$update_date = get_the_modified_date( 'd/m/Y', $post->ID );

return "Published on: " . $publication_date . ". Last update: " . $update_date . ".";
}
add_shortcode('dates', 'dates_shortcode');

With the previous shortcode, when you write [dates] in a post or page, the publication date and the last update date of that particular post will be displayed.

It is important to note that this code uses a specific date format (d/m/Y), which represents day/month/year. If you prefer another format, simply change that part of the code.

How to Check if Google is Indexing Content Generated by Shortcodes from Elementor, RevSlider, and Other Plugins?

Correct indexing of content on your website is essential to ensure optimal visibility in search engines. When you use tools like Elementor or RevSlider to create and customize your site, shortcodes are often generated that display dynamic content behind the scenes. Here is a guide to ensure that Google and other search engines are reading and indexing this content properly:

  1. Mobile-Friendly Test: One of the most effective tools provided by Google. Simply enter your page’s URL at Mobile-Friendly Test and analyze the results. This tool will not only tell you if your page is mobile-friendly, but it will also show how Googlebot sees and renders your page.
  2. URL Inspection in Google Search Console: If you have already verified your site on Google Search Console, you can use the “URL Inspection” tool to see how Google views a specific page. It provides details about crawling, indexing, and delivering pages on your site.
  3. View Source Code: In your browser, go to the page you want to check. Right-click and select “View page source code”. Look for the shortcode itself (e.g., [elementor-id] or something similar). If you can’t see the rendered content in the source code, it means the content is loaded via JavaScript. However, this doesn’t necessarily mean Google can’t see it, thanks to its advanced rendering capabilities.
  4. Avoid Blocking JavaScript: Make sure you’re not accidentally blocking JavaScript files in your robots.txt file. Google needs access to these files to render and understand pages that depend on JavaScript.

Cleaning Up Shortcodes When Disabling a Plugin

When a plugin that provides certain shortcodes is disabled, these can appear as plain text in your posts or pages. It is essential to be aware of this and take the necessary measures to clean up or replace those shortcodes. A tool or plugin that detects unused shortcodes can be very helpful in this process.

Potential Security Issues with Shortcodes

While shortcodes are powerful and flexible, they can also pose vulnerabilities if not implemented correctly. It’s crucial to ensure that any custom shortcode you add or any plugin you use is well-coded and doesn’t pose security risks. We recommend regularly reviewing and testing your shortcodes and, if possible, consulting with WordPress security experts.

Benefits and Challenges of WordPress Shortcodes

Shortcodes offer a quick and efficient solution to add functionalities. However, it is crucial not to overuse them, as too many shortcodes can affect your site’s performance.

  • Pros: Ease of use, adaptability, customization.
  • Cons: Possible impact on site speed, dependence on plugins for certain shortcodes.

Final Conclusions

In conclusion, shortcodes stand as fundamental pillars to enhance and simplify the functionality of your WordPress website. From creating interactive elements to inserting multimedia content, shortcodes offer an effective way to enrich the experience of your visitors. If you want to explore more about the foundations of web creation and how they combine with WordPress capabilities, I invite you to visit our article on WordPress Deep Dive.

Autor
Alejandro Frades
Marketing Specialist
The mind behind Modular's social content. Always on top of the latest trends to take advantage of them and make the digital world more enjoyable and entertaining.

Subscribe to our Newsletter about the web world