How to create a shortcode with attribute in WordPress


Sometimes you need a functionality which you need to display on website again and again.

One simplest approach is write the implementation of your required stuff again and again but this can make your code complicated and if you wish to make any change in it, you will have to make changes in every location. So, this is not a good approach in terms of time and efficiency.

The best solution is do via shortcode.

A shortcode is a WordPress-specific code that lets you do nifty things with very little effort. Shortcodes can embed files or create objects that would normally require lots of complicated, ugly code in just one line.

Lets take a simple example here:



  function create_custom_headings($atts){
    $value = shortcode_atts( array(
        'title_1' => '',
        'title_2' => ''
    ), $atts );

    $return = '<h1>'.$value['title_1'].'</h1><h2>'.$value['title_2'].'</h2>';

    return $return;

  add_shortcode('heading', 'create_custom_headings');



The usage is below:

If you do it as widgets or in content section:

[heading title_1="I am first title" title_2="I am second title"]


If you wish to make it as part of template:

   do_shortcode('[heading title_1="I am first title" title_2="I am second title"]');



Related Posts