How to make a shortcode from PHP

Learn how to create a Shortcode from PHP with an example. Unlock the power of shortcodes to add custom content to your WordPress site.

Creating a Shortcode From PHP

Shortcodes are a great way to add dynamic content to WordPress pages and posts. They are a simple and powerful way to quickly add custom functionality to a page or post without having to write a lot of code. In this tutorial, we will show you how to create a shortcode from PHP.

First, let's create a simple function that will output some HTML when called. We'll give the function a name of “my_shortcode” and it will take two arguments: “text” and “color”.


function my_shortcode($atts) {
    extract(shortcode_atts(array(
        'text' => 'Hello World',
        'color' => 'red',
    ), $atts));
 
    $output = ''.$text.'';
 
    return $output;
}
add_shortcode('my_shortcode', 'my_shortcode');

The function takes the two arguments, “text” and “color”, and uses the extract() function to assign them to variables. If a value is not passed in, a default value is assigned. The $output variable is then set to a string containing the HTML for the output. Finally, the add_shortcode() function is used to register the shortcode with WordPress.

Now that the function is registered, we can use it in our posts and pages. To do this, we simply need to write the shortcode with the desired arguments in the post or page:


[my_shortcode text="Hi there!" color="blue"]

This will output the following HTML:


Hi there!

And that's it! You've successfully created a shortcode from PHP. Shortcodes are a great way to quickly add custom functionality to your WordPress site with minimal effort.

Answers (0)