How to create your own WordPress shortcodes (Easy Steps)

How to create your own WordPress shortcodes (Easy Steps)

To create a shortcode in WordPress that allows you to change a value from your code, you can use the following steps:

  1. Define the shortcode in your theme’s functions.php file using the add_shortcode function.
  2. In the shortcode function, you can retrieve the value you want to change from your code and return it within the shortcode output.
  3. You can also allow users to pass attributes to the shortcode to dynamically change the value that is returned.

Example code:

function my_shortcode_function( $atts ) {
   $atts = shortcode_atts( array(
      'value' => 'default_value'
   ), $atts );
   return $atts['value'];
}
add_shortcode( 'my_shortcode', 'my_shortcode_function' );

You can then use the shortcode in your posts and pages like this: [my_shortcode value="new_value"] and it will return the new value “new_value”.

Video Tutorial

The following shortcode function if for download button which I created in earlier video.

Blog post link is follows:
Create download button with countdown timer

function my_shortcode_function( $atts ) {
   $atts = shortcode_atts( array(
      'value' => ''
   ), $atts );
   $mycode = '<div class="btn-container">
      <a class="download-btn" data-href="'.$atts['value'].'"> 
        <i class="fa-solid fa-cloud-arrow-down"></i> Download Now 
      </a>
      <div class="countdown"></div>
      <div class="pleaseWait-text">Please Wait...</div>
      <div class="manualDownload-text">Direct Link <a class="manualDownload-link">Click Here</a></div>
   </div>';
   return $mycode;
}
add_shortcode( 'code_download_btn', 'my_shortcode_function' );

This code defines a shortcode in WordPress named code_download_btn which generates HTML code for a download button.

The shortcode function my_shortcode_function takes an array of attributes $atts as its parameter. It uses the shortcode_atts function to merge any attribute values passed to the shortcode with a default array that sets the value of value to an empty string.

The function then generates HTML code for a download button using the attribute values, if provided, for the data-href attribute of the download button. The generated HTML code includes a countdown, a “Please Wait…” message, and a “Direct Link” message with a link to manually download the file.

Finally, the generated HTML code is stored in the $mycode variable and returned to be displayed on the page whenever the shortcode is used. The add_shortcode function registers the shortcode with WordPress and associates it with the my_shortcode_function function as its handler.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *