I am working on building some shortcodes for my blog.
I can set a single parameter for my shortcode, but not sure how to set different parameter.
For example, I can use [myshortcode myvalue]
to output a html block within the post content.
Here is what I am currently using:
function test_shortcodes( $atts ) {
extract( shortcode_atts( array(
'myvalue' => '<div class="shortcodecontent"></div>'
), $atts ) );
return $myvalue;
}
add_shortcode( 'myshortcode', 'test_shortcodes' );
Now, how can I use [myshortcode myothervalue]
to output a different block of html?
Please note that the shortcode is same, only the parameter is changed.
Lets look at the shortcode
the shortcode handler function accepts 3 paramters
$atts
– an array of attributes passed by the shortcode in our case:$atts['var1']
is set to'somevalue'
$atts['var2']
is set to'someothervalue'
$content
– is a string of the value enclosed with in the shortcode tags, in our case:–
$content
is set toTHE SHORTCODE CONTENT
$tag
– is a string of the shortcode tag, in our case:–
$tag
is set toSH_TEST
When I create a shortcode i usually define the default values and merge them with the values submitted by the shortcode tag ex:
If you use the shortcode like that
atts[0]
will contain the value:Another way is calling the value with a name:
You’re better off doing it like this:
Use it like this:
[myshortcode type="myvalue"]
to output<div class="shortcodecontent"></div>
and
[myshortcode type="myothervalue"]
to output<div class="othershortcodecontent"></div>
This way works for me in all cases using [myshortcode type=”myvalue”]
And if you want to add another parameter all you need to do is this [myshortcode type=”myvalue” other=”somevalue”]
I hope this helps
First, you will have to define $atts item in your function because $atts is an array.
Here is the complete code to pass the variable in shortcode –
Let’s suppose you need to show all the product of a category through shortcode, You need to do following code in your function file –
Now you can simply paste the shortcode code in your template file or WordPress default editor –
Where we’re passing the Category name (creative-writing-english-literature) in the shortcode.
Have tested it and it’s working.