How to Create a Custom WordPress Shortcode

by | Dec 28, 2024

Today’s tutorial is going to be one of my favorites because we’re diving into a blend of PHP, HTML, and CSS in a short amount of time. We’ll create a custom WordPress shortcode that displays a block of text, styled to look like an iPhone text message. Here’s a sneak peek of what it will look like when we’re done!

This approach is my favorite way to learn. I never attended a boot camp or took classes for any of these programming languages or WordPress development. My curiosity drove me to figure it out over time through small projects. I believe working on projects fueled by your own ideas is far more rewarding than simply taking a boot camp to add a skill to your resume.

Getting Started with Shortcodes

We’ll accomplish this through the functions.php file within your theme directory. If you’re a developer, you’re likely familiar with this, but if you’re a beginner, you might wonder, “What is that?” Regardless of your experience level, let’s get started on this project.

I’m currently on a WordPress post page, and this is where we’ll begin. The first step in creating a shortcode is to start with plain HTML. Once the HTML and CSS are harmonized, I can convert them into PHP code and include a few options.

Creating the HTML Structure

I want to add a custom HTML block here to paste in the HTML code. It’s simple: a <div> with a class of "imsg" for iMessage. There will also be a second class, "first", to designate the sender of the first message, and a third class called "reply" to determine whether the message appears in blue or gray.

Once I save this, I’ll add custom CSS in the appearance section. I usually do this from the child theme’s style.css file, but there are typically two or three places where you can add custom CSS. For today, I’ll paste this in the additional CSS section. While I won’t dive into it in detail now, I’ll step through some of these CSS styles at the end of our project.

Building the Shortcode

Now, let’s move on to building the shortcode. When I work on custom code like this, I often search for others who have used similar functions or tackled the same goal. I found this helpful website to generate your shortcode template. You fill in your details, and it builds your PHP code to add to the functions.php file.

I’ll start on the shortcode tab. The first step is to fill out the shortcode name we’ll use; I’ll call it "imsg". For the function name, I’ll append "_shortcode" to it, replacing "custom" with "imsg". This site provides examples of both self-closing and enclosing shortcodes, but we want the enclosing type since the content will be the text message.

Next, I’ll select “enclosing” and build in one attribute: whether it’s a reply. If it’s a reply, it’ll be gray; if not, it’ll be blue. Moving on, I’ll define our attributes, naming this one "reply" (all lowercase) and setting its default value to false. Essentially, if the shortcode has the option reply=true, it will use the reply style.

Let’s update this code and grab our skeleton code to work with, pasting it into the functions.php file. You can access the functions.php file from the appearance editor; it’s usually right under the style.css. Scroll down to the bottom, and we’ll add our custom code there.

If you want to read more about how this works, WordPress has a page in their Codex section. If you Google “WordPress shortcode API,” you’ll find it. This resource describes some of the options we’ll cover. I won’t go into a full-length explanation, but it’s a great starting point if you need something specific and aren’t sure where to look.

Understanding the Code

To summarize quickly: we’re providing a function to add a shortcode. This is our custom function, and we use the WordPress function add_shortcode to attach it to the WordPress system, allowing us to use it within posts and pages. There are two arguments: the first is the attributes (the options we define within the shortcode), and the second is the content (what the shortcode wraps around, essentially our text message).

Next, we define our default values. If the reply value isn’t set within the shortcode, it defaults to false. If we want to manually change that to true, we have to do it within the shortcode. I may not be the best at explaining this, so if any experienced developers come across this, feel free to leave a comment with your insights.

Now, we need to add a bit of logic. We have to check the reply option and determine what to do based on that. Checking the reply option will only take a single line of code. I like to comment on each section, so I’ll start with two forward slashes to begin a comment line and write something descriptive as a reminder for later.

I’ll create a variable called $msg_type, which will hold the string of the class we’ll add to the <div>. I’ll use a one-line if-else statement for this. The framework is to put a conditional statement in parentheses, followed by a question mark. If the conditional statement passes (is true), we assign the first value; if it’s false, we assign the second value.

Let’s start with the conditional statement. I’ll use a function that removes links from a string of text: esc_attr. We’ll put our attributes array inside this function. To get the value for the reply option, we’ll use square brackets and single quotes: ['reply']. This gives us the value, either false (the default) or whatever we define it as within the shortcode.

I want to check if this is true. We’ll use two equal signs and look for the string "true" surrounded by quotes. While I could discuss comparisons and logic in PHP in detail, I’ll keep this brief to maintain our pace.

So, if this is true, we add the class "reply". If it’s not, we add the class "first". This line should be complete, and now we need to return our value. If you’re familiar with coding, you know the return function will return a string of code, and we’ll place our variables within that.

I’ll copy the pure HTML code we had earlier and replace the class with our variable. To break this string, I need to add two single quotes. In PHP, opening strings start with a single quote, and within our HTML, we’ll use double quotes for anything inside that. This can be confusing and lead to errors in PHP code, so I’ll add the two quotes to break this up. To concatenate strings in PHP, we use the period operator.

I’ll concatenate the first part of the string with our variable $msg_type, and then concatenate the second part of the string. We also need to replace the hard-coded message with our content in the same way, using two single quotes to break it up.

Let’s save this and head to the post where we currently have the plain HTML code. I’ll replace that with the shortcode. I’ll copy and paste it, removing the block and adding a shortcode block instead. I’ll substitute the HTML with the shortcode and do the same for the closing tag. Since we haven’t set any options yet, the message should appear in blue.

Let’s update this post and see how it looks. If all goes well, we’ll end up with our iPhone-style messages. If something seems off, let’s troubleshoot. Nothing ever goes perfectly! At first glance, I see there’s no space between the classes. I forgot to add that space, so let’s correct that.

Now I’ll add another reply to see both styles in action. I’ll copy this, insert another shortcode element, and paste it in. I’ll place a longer message after filling out the option. I just need to add reply=true with double quotes around that string. Let’s save the page and check it out.

And there you have it! As promised, let me quickly dive into the CSS and explain the different styles I applied without getting too deep into the syntax. There are three main parts to this:

  • Styling the Containers — We apply CSS properties to either element. We set the position: relative to enable absolute positioning for sub-elements. We adjust the font size, set the font family to a sans-serif font, and tweak the line height, border radius, and padding.
  • Creating the Arrows — The arrows, positioned using CSS, are generated with the ::before and ::after pseudo-elements. These are absolutely positioned with a height and width of 0, and their color is created through borders.
  • Setting Backgrounds and Colors — The code for the first message sets the background to blue and the font color to white. We apply a custom margin to offset it to the right, and the blue arrow is created using borders, while similar styles are used for the reply element with different values.

I’ll include a link below to download all the code. You can copy and paste it into your project!

I hope you found this tutorial valuable! It was a game-changer when I first learned about custom shortcodes, especially since I was really into coding.

If you have skills in building websites and working with WordPress and want to start freelancing to monetize those skills, check out the rest of my blog.

Overall, I’ve found the most success working with local clients. Many small businesses struggle with a weak web presence and need your help. They don’t hire web developers easily; it takes time to build trust. That’s why I recommend focusing on the local aspect—you can converse with them over the phone or even meet in person.

Categories

×