WordPress Shortcodes: How to Create Reusable Components in WordPress
Tags: wordpress, react, php, webdev
Published: 2023-09-17 18:19:24

A few days ago, I was working on a [simple blog project](https://androidsy.com) using WordPress and I needed a way to make reusable patterns or "_**shortcodes**_" just like we easily do with [React components](https://dev.to/stephengade/reactjs-tutorial-for-beginners-build-your-first-react-application-part-2-4joc) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lds60pnfux7of3hdszar.png)
**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](https://wordpress.org/gutenberg/) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u5ir5q3xh346cdi6kd5b.png)
**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:

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

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

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:

```php
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
}
```

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

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

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


```php
// 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;
```

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/otvqhn4me1aa5zbjhubd.png)

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

```php
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');
```

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:

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

...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.