Back to all posts

How to Create a Shortcode in WordPress


In WordPress, a shortcode is a small piece of code enclosed in square brackets that allows users to easily embed dynamic content or functionality within their posts, pages, or widgets.

We can create shortcode direct inside functions.php file but files get pretty big and hard to manage.

So we will follow step by step approach to create custom post type.

Note: Before you start, take backup your wordpress site.

Step 1 – Create a New File.

Navigate to wp-content > theme > present working theme

Create folder with name “shortcode” inside this folder create new file with name you like. I will choose “custom_shortcode.php”

After creating this folder, Open the functions.php file of your theme and add follwing code at bottom of the document.

/**
 * Importing shortcode files
 */

require_once("shortcodes/custom_shortcode.php");

Step 2 – Create the Shortcode Function

Next, you’ll need to create the shortcode’s function, commanding it what to do.

Open custom_shortcode.php file in code editor and add below code

<?php

function greeting_callback()
{
    return 'Good Morning';
}

add_shortcode('greeting', 'greeting_callback');

This is a basic example of creating shortcode

In above example we register shortcode using the add_shortcode() function is used to register a shortcode with a specific name and a corresponding callback function.

The add_shortcode() function takes two arguments:

  1. $tag (required): A string that specifies the name of the shortcode that you want to register. This should be a lowercase string with no spaces or special characters, and it should be unique within your WordPress installation. in our example “greeting”
  2. $callback (required): A callback function that is executed when the shortcode is used in a post, page, or widget. This function should generate and return the content that you want to display when the shortcode is used in our example “greeting_callback”.

Step 3 – Add Shortcode to the Website

Now you can use default block editor widget called shortcode add this shorcode

Result

In case if you want use this shortcode inside custom code you can use below code and add your shortcode

do_shortcode ("[your_shortcode]");

If you not returning in your shortcode function you need to write echo

echo do_shortcode ("[your_shortcode]");

Step 4 – Add Parameters to the Shortcode

If you want to display name in greeting you can do with help of parameters.

For example “Good Morning Chethan”

Add following code

<?php

function greeting_callback($atts)
{
    $atts = shortcode_atts(array(

        'name' => 'World',

    ), $atts);

    
    return 'Good Morning '. $atts['name'];
}

add_shortcode('greeting', 'greeting_callback');

shortcode_atts() this function assign default value if Parameters are not given to shortcode.

Read more about shortcode_atts() here

[greeting name='Chethan']

Now the shortcode look like this

Read More About Shortcode


This is complete example of short code with product post type data in return.

<?php



function product_slider_callback($atts)
{



    $atts = shortcode_atts(array(

        'category' => 'Uncategorized',

    ), $atts);

    $args = array(
        'post_type' => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => $atts['category'],
            )
        )
    );

    $products = new WP_Query($args);

    ob_start(); ?>
    <div class="owl-carousel">
        <?php
        if ($products->have_posts()) {
            while ($products->have_posts()) {
                $products->the_post();
                // Do something with each product here
        ?>
                <div> 
                    <?php if (has_post_thumbnail()) : ?>
                        <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                            <img src="<?php echo get_the_post_thumbnail_url(get_the_ID(), 'thumbnail'); ?>" alt="<?php the_title_attribute(); ?>">
                        </a>
                    <?php endif; ?>
                    <h2>
                        <?php the_title(); ?> 
                    </h2>
                </div>

        <?php }
        } else {
            // No products found
            echo "No Product available";
        }

        // End the post loop
        wp_reset_postdata();
        ?>

    </div>



<?php

    // Get the contents of the output buffer and assign it to a variable

    $slider = ob_get_clean();



    return $slider;
}



add_shortcode('product_slider', 'product_slider_callback');



?>

Shortcode with parameter

[product_slider category="book"]