Calling a function from post or page content

Just add [my_special_shortcode] within any post or page and the function will be called

//Shortcode: [my_special_shortcode]
add_shortcode('my_special_shortcode', 'my_function_Name');
function my_function_Name()
{

  //-----------------------
  //----- HTML OUTPUT -----
  //-----------------------
  $HtmlOutput = '';

  return($HtmlOutput);
}

Passing arguments with a shortcode

In the wordpress content

(N.B. keep attributes lowercase, they will get converted to lowercase)

[my_special_shortcode my_id=12 my_value="abc"]

In your function

add_shortcode('my_special_shortcode', 'my_function_Name');
function my_function_Name($atts)
{
  //----- GET SHORTCODE ATTRIBUTES -----
  //Extract attributes, setting default values if not present
  extract(shortcode_atts(array(
    'my_id' => 1,
    'my_value' => ''
  ), $atts));

  //if ($my_id == 12)
  //...

  //-----------------------
  //----- HTML OUTPUT -----
  //-----------------------
  $HtmlOutput = '';

  return($HtmlOutput);}
Other things you can pass with a shortcode

https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

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