How to Create Custom Shortcodes In WordPress

What is a Shortcode?

A shortcode in WordPress is a small piece of code, indicated by brackets [ ]. Shortcodes can be inserted into pages, posts, and widgets to execute predefined scripts that add dynamic content or functionality without writing long blocks of code directly into each post or page. You can add them to your plugin to make it easy for users to add your custom features to their website. Shortcodes simplify the process of adding complex or repetitive content and functionality to a WordPress site, making them a powerful tool for users who may not be familiar with programming.

If your looking to elevate your site with a custom plugin that does exactly what you need.
Contact us to start your custom plugin project today!

Creating Custom Shortcodes In WordPress

How to Create Custom Shortcodes

Developers can create custom shortcodes by writing a function in PHP that defines what the shortcode does and then registering it with WordPress using the add_shortcode() function. This allows for adding highly customized functionality to a WordPress site that can be reused across multiple pages and posts by simply including the shortcode. 

Simple Shortcode Example

function custom_message_shortcode() { 
return "Welcome to my WordPress site!"; 
}

add_shortcode('custom_message', 'custom_message_shortcode');

Add shortcode to page

[custom_message]

How does it work?

custom_message_shortcode()

This function will output the content that the shortcode will display on the front end.

add_shortcode()

Use the function to register your shortcode, specifying the shortcode tag (e.g., custom_message) and the function that it should execute when called.

[custom_message]

Now, you can use the shortcode in your posts, pages, or widgets. When viewed on the front end, it will display the text "Welcome to my WordPress site!"

Create a Shortcode With Attributes
AKA Shortcode Settings

Creating a WordPress shortcode with attributes allows you to make your shortcodes more flexible and dynamic. Attributes work like options that can be set when the shortcode is used, giving the user control over what the shortcode outputs without altering the underlying code.

Create a Shortcode With Attributes

function custom_greeting_shortcode($atts) {
    // Set default values for attributes
    $atts = shortcode_atts(
        array(
            'name' => 'User',     // Default name if none provided
            'color' => 'black'    // Default text color
        ),
        $atts,
        'greeting'
    );


    // Create the output string with the attributes
    $output = '<span style="color: ' . esc_attr($atts['color']) . ';">';
    $output .= 'Hello, ' . esc_html($atts['name']) . '!';
    $output .= '</span>';


    return $output;
}
add_shortcode('greeting', 'custom_greeting_shortcode');

Add shortcode to page

[greeting name="Nathan" color="blue"]  // Output: Hello, Nathan! (in blue color)

How does it work?

shortcode_atts()

This function merges user-provided attributes with known defaults. It ensures that all attributes have a value and prevents users from entering attributes that are not explicitly handled by your function.

esc_attr():

This function ensures that the color attribute is safe to include in HTML output (avoiding XSS vulnerabilities).

esc_html():

This function ensures that any text added to the output is safe from HTML and JavaScript execution, which is crucial for security.

Why Escaping User Input is Essential for Security

In web development, securing output is crucial, especially on platforms like WordPress that handle user input. Functions like esc_attr() and esc_html() are essential for preventing security vulnerabilities such as cross-site scripting (XSS) attacks. In a nut shell it helps stop hackers from Injecting malicious code onto your website. Using these functions allows developers to safely display user-generated content, maintaining a secure and reliable website.

Create an Enclosing Shortcode

An enclosing shortcode allows you to wrap content inside the shortcode tags, which can then be manipulated or formatted by the shortcode's functionality.

Enclosing Shortcode Example

[styled_content color="red" background="yellow"]
This is my custom styled content!
[/styled_content]

Enclosing Shortcode Example

// Register the enclosing shortcode
function custom_styled_content_shortcode( $atts , $content = null ) {
    // Attributes
    $atts = shortcode_atts(
        array(
            'color' => 'blue', // Default color
            'background' => 'none', // Default background
        ),
        $atts,
        'styled_content'
    );

    // Return the formatted content
    return '<div style="color: ' . esc_attr( $atts['color'] ) . '; background: ' . esc_attr( $atts['background'] ) . ';">' . do_shortcode($content) . '</div>';
}

// Add shortcode to WordPress
add_shortcode( 'styled_content', 'custom_styled_content_shortcode' );

How does it work?

$content The content between the shortcode tags is automatically passed to the function. For example, in [styled_content]Hello, world![/styled_content], "Hello, world!" is passed as $content.

$content = null The $content parameter is initialized with null to handle cases where no content is enclosed.

do_shortcode($content)This function allows any WordPress shortcodes contained within the $content to be executed. Essentially, this means that if your enclosed content has other shortcodes, they will be processed and executed as part of the output.

Efficient HTML Handling with Output Buffering in WordPress

In the given shortcode example, ob_start() initiates buffering, allowing PHP to hold all echoed HTML content. After some initial content is buffered, ob_clean() is used to clear that content from the buffer, effectively removing what was initially buffered. More content is then added to the buffer. Finally, ob_get_clean() captures the new content, clears the buffer, and the captured content is returned to be displayed wherever the shortcode is used in WordPress. This setup is particularly useful for generating complex or dynamic HTML structures in a clean and controlled manner within a shortcode.

Shortcode Example With Output Buffering

function custom_dynamic_content_shortcode() {
    // Start output buffering
    ob_start();

    // Your HTML content
    echo '<div>';
    echo '<p>This is some dynamic content generated by a shortcode.</p>';
    echo '</div>';

    // Clean (erase) the output buffer and turn off output buffering
    ob_clean();

    // Generate more content
    echo '<div>';
    echo '<p>More content added after cleaning the buffer.</p>';
    echo '</div>';

    // Return the contents of the output buffer and end output buffering
    $output = ob_get_clean();
    return $output;
}

add_shortcode('dynamic_content', 'custom_dynamic_content_shortcode');

How does output buffering work?

ob_start() This function starts output buffering. Instead of sending output to the browser immediately, PHP keeps it in a buffer. This allows you to manipulate the output before it's sent to the client.

ob_clean() After starting output buffering with ob_start(), ob_clean() clears the content of the output buffer without stopping the buffering. In essence, it erases the current contents of the buffer but does not output them or end the buffering. This can be useful when you want to discard some generated content before producing the final output.

ob_get_clean()This function retrieves the content from the buffer and then cleans (erases) and closes the output buffering. It is typically used at the end of your function to capture all the buffered output into a variable, clean the buffer, and then return the captured content as part of the function's return value.

Check out our FREE ONLINE
WordPress Plugin Development Course

Looking to develop a custom plugin, or create new features for your website?

Facebook Video