We will see how to pass parameters in short-code, How to assign default values to parameters and How to use separate files to create a long html.
Now we know the basis short-code function add_shortcode(‘shortcode tag’, ‘callbackfunction’)
Now we are passing the parameters to short-code so we need to do :
- First change the case of attributes like title == TITLE == Title as short-code attribute
- Overwrite the default value of attributes with user values. So if user attributes are not defined, it will take default values.
Remember each callbackfunction must return something.
We can use short-code [test-pluugin] to see result on any page.
function callback_shortcode($atts)
{
return '<h1>How are you world?</h1>';
}
add_shortcode('test-plugin', 'callback_shortcode');
Now let’s pass some attributes(key-value pairs) so this is the updated code:
function callback_shortcode($atts)
{
// normalize attribute keys, lowercase
$atts = array_change_key_case($atts, CASE_LOWER);
// override default attributes with user attributes
$atts = shortcode_atts(array(
"name" => "Not declared",
"jobdesc" => "Default as Author",
"salary" => "000"
), $atts);
return "<h1>Here is one user data: Name is $atts[name], his job profile is $atts[jobdesc] and he earns $atts[salary] per anum</h1>";
}
add_shortcode('test-plugin', 'callback_shortcode');
Try to check this short-code with attributes & without attributes. Please note that where the attributes are not defined (Key-value pair, it takes the default values we defined in shot-code function.
[test-plugin name=”Dilip Parmar” jobdesc=”Software Engineer” Salary=3lac]
[test-plugin]
Now if your html file is going to be long, You can create a separate file in plugin folder and include it into function before return statement. But Please note you have to use ob_start() before include and after include use ob_get_clean() functions. If you do not do this, your html will display on top of the page, not in between the page content.
Using ob_start() and ob_get_clean() allows you to return HTML code from the short-code.
So just create a separate file and include it to function.
function callback_shortcode($atts)
{
// normalize attribute keys, lowercase
$atts = array_change_key_case($atts, CASE_LOWER);
// override default attributes with user attributes
$atts = shortcode_atts(array(
"name" => "Not declared",
"jobdesc" => "Default as Author",
"salary" => "000"
), $atts);
ob_start();
include 'users.php';
$html = ob_get_clean();
return $html;
}
add_shortcode('test-plugin', 'callback_shortcode');
So now we know:
How to create a short-code,
How to use it in page,
How to pass attributes into short-code with default values
How to include separate HTML file in short-code
That’s it!