Adding a shortcode to your wordpress website

You can add a shortcode to your wordpress site very easily using a function

  1. Use the add_shortcode function to register the shortcode function
  2. Define the shortcode function
  3. Return a value in shortcode function to replace the shortcode value

 

 PHP |  copy code | ?
1
<?php
2
add_shortcode('Myshortcode', 'shortcode_function');
3

4
function shortcode_function($attr){
5

6
return "MyShortcode has been replaced by shortcode function";
7
}
8

9
?>

You can also use functions within a class as shortcode function too. For the just use the shortcode function name as array with first element in array signifying classname and second one defines the class function

 PHP |  copy code | ?
01
<?php
02

03
add_shortcode('MyshortcodeinClass', array('MyClass', 'shortcode_function');
04

05
class MyClass{
06
  function shortcode_function($attr){
07
    return "This is the value returned by the shortcode MyShortCodeinClass";
08
  }
09
}
10
?>