DEV Community

Stephen Gbolagade
Stephen Gbolagade

Posted on

WordPress Shortcodes: How to Create Reusable Components in WordPress

A few days ago, I was working on a simple blog project using WordPress and I needed a way to make reusable patterns or "shortcodes" just like we easily do with React components with lifting or passing props. But WordPress is built with PHP, meaning I can't really perform the prop-lifting magic on the project. After doing some research online, I figured out how to do it!

To understand if this article is for you, here is what I was trying to achieve πŸ‘‡

Product recommendation card
Image credit: AndroidPolice

As you can see this card is recommending products to readers, and of course the content will change with respect to what the topic is all about. I know you're pretty familiar with product recommendation cards like this. That's exactly what I was trying to do on WordPress.

Typically, there are 3 methods to create reusable components in WordPress namely:

  • Using Gutenberg Block Editor
  • Using Plugin
  • Tweaking the WordPress theme's code

If you are using Gutenberg editor on your WordPress website, simply select the block you would like to create a pattern for, then click the three dots at the top-right corner of the block editor and click "Create reusable block".

Create Reusable block in WordPress
Image credit: WP Beginner

With that, you can always import the reusable block in any post and customize it.

This doesn't work for me as I am not a fan of Gutenberg Editor (I use Classic Editor). So I veered to WordPress plugins but I found none. Most WordPress plugins for creating shortcodes will ask you to upgrade to the PRO version before you are granted access to create your desired shortcode or pattern.

Then I had to go for the third option, which is to tweak the PHP which is most easy.

If this is what you've been looking for, worry no more! In this technical guide, I will walk you through the process of creating these reusable components in WordPress, enhancing your website's functionality and maintainability.

Before you start, ensure the following:

  • Have Admin access to the WordPress website
  • Backup your website
  • Understand HTML, CSS, and a little PHP (You can flow with the code too, it's simple)

LET'S GO!

Step 1: Define the Structure of Your Reusable Component

Before you do anything, take a moment to plan the pattern. Identify the specific functionality or content you want to display to the readers. Consider any customization options (parameters) users may need when using your shortcode.

Step 2: Write the PHP Function

To create a shortcode in WordPress, you need to define a PHP function. This function will generate the HTML or content that your shortcode will render. Here's a basic template for a shortcode function:



function my_shortcode_function($atts) {
  // Your shortcode's HTML generation code goes here
}

// register your function here
add_shortcode('my_shortcode', 'my_shortcode_function');


Enter fullscreen mode Exit fullscreen mode

In this template, replace my_shortcode with the name of your shortcode and add your HTML generation code inside the function.

Step 3: Define Parameters

If you're a React or JavaScript developer, just take this as your props or the usual JavaScript parameters you are familiar with.

WordPress shortcodes can accept parameters (attributes) to customize their behavior. Use the shortcode_atts function to define default values for parameters. Here's an example:



function my_shortcode_function($atts) {

// Extract shortcode attributes

extract(shortcode_atts(array(
'title' => 'WordPress Charging Cord',
'link' => 'https://dev.to',
), $atts));

// Use $atts['title'] and $atts['link'] in your HTML generation code
}


Enter fullscreen mode Exit fullscreen mode

Here, we simply create a placeholder $atts and map it to our custom keys and value. Our keys are "title" and "link", while we passed default values to them which you can always change when using the shortcode.

We used extract keywords just like we do export in JavaScript.

Step 4: Generate HTML

Inside your shortcode function, generate the HTML or content that your shortcode will render based on the parameters provided. Customize this code to match your specific component or structure.

Here is what we want to generate



<div class="recommendation-card">
   <h3> Title </h3>
    <a>Link</a>
</div>


Enter fullscreen mode Exit fullscreen mode

But that's just HTML and won't work if you do it like that. Here is how to generate the result



// Generate the HTML for the product recommendation card

$output = '<div class="recommendation-card">';
$output .= '<h3>' . esc_html($title) . '</h3>';
$output .= '<a href="' . esc_url($link) . '" class="product-link">Buy now</a>';
$output .= '</div>';

return $output;


Enter fullscreen mode Exit fullscreen mode

Step 5: Put the full code on your website.

Log in to the Admin dashboard, go to Appearance, go to Theme Editor, and find function.php at the right sidebar.

WordPress function.php

Scroll down and put the full code there. Here is the full code:



function my_shortcode_function($atts) {

// Extract shortcode attributes

extract(shortcode_atts(array(
'title' => 'WordPress Charging Cord',
'link' => 'https://dev.to',
), $atts));

$output = '<div class="recommendation-card">';
$output .= '<h3>' . esc_html($title) . '</h3>';
$output .= '<a href="' . esc_url($link) . '" class="product-link">Buy now</a>';
$output .= '</div>';

return $output;
}


// register your function here
add_shortcode('my_shortcode', 'my_shortcode_function');


Enter fullscreen mode Exit fullscreen mode

Once you put it there, click on Update File and you are good to text your shortcode.

Step 6: Use Your Reusable Component

You can now use your shortcode within your WordPress posts, pages, or widgets. To use it, simply enclose the shortcode name in square brackets and customize the parameters as needed. Here's an example of usage:



[my_shortcode title="Stephengade Blog" link="https"//dev.to/stephengade"]


Enter fullscreen mode Exit fullscreen mode

...and you can use the shortcode as much as you like.

Don't forget that you can also style your style with CSS. Simply Log in to your WordPress again >> Appearance >> Customize. Then scroll down and click "Advance CSS" to write your CSS code, and click "PUBLISH" when you are done.

Harness the Power of Reusable Components

Creating reusable components in WordPress using shortcodes is a valuable skill for developers and content creators. It streamlines your website development process, promotes consistency, and simplifies maintenance.

By following this step-by-step guide, you can enhance your WordPress site with custom, reusable functionality, making your web projects more efficient and user-friendly.

Top comments (2)

Collapse
 
dllhnnx profile image
DLLhnnx • Edited

If you're using a page builder (elementor, divi, beaver builder) don't forget about overbufer before and after the closing php tags, otherwise all the content will be displayed above the_content();

function myShortcode(){
    ob_start();?>
    // -> your html content
 <?php ob_get_clean(); }
add_shortcode('myShortcode', 'myShortcode');
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stephengade profile image
Stephen Gbolagade

Thanks for the contribution πŸ™