I have below a shortcode on my page.
[singletextutm url="/about-us/" name="Know more" class="no-bg-button" ]
I am using the below code in the function.php and it’s working
function singletextutmlink($atts, $content='') {
$atts = shortcode_atts(
array(
'url' => '',
'name' => '',
'class' => '',
'icon'=> '',
), $atts);
if ($atts['icon'] == 0) {
$ctaicon ='';
}
else {
$ctaicon ='<i class="fas fa-arrow-right"></i>';
}
return $ctaicon;
}
add_shortcode( 'singletextutm', 'singletextutmlink');
Now my issue with the below code. I haven’t added an icon attribute to my shortcode because I have to set the default icon attribute. I mean if the icon attribute is not added in the shortcode then still it should run the else condition.
if ($atts['icon'] == 0) {
$ctaicon ='';
}
else {
$ctaicon ='<i class="fas fa-arrow-right"></i>';
}
The expected output in the comment
[singletextutm url="/about-us/" name="Know more" class="no-bg-button" icon="0"] // it will display empty $ctaicon
[singletextutm url="/about-us/" name="Know more" class="no-bg-button" ] // Not set icon but still run else conditon <i class="fas fa-arrow-right"></i>
[singletextutm url="/about-us/" name="Know more" class="no-bg-button" icon="1"] // it will display <i class="fas fa-arrow-right"></i>
4
Answers
You can try
First param of
shortcode_atts
means the default k-v, it set the default value oficon
to null now, so that only if someoneadd the icon attribute to 0 it will return ”.
It totally work on my side –
With this shortcode –
You need to set a default in your
shortcode_atts
.'icon' => '0'
This sets the icon to be the character (not the integer) ‘0’. Then when you’re comparing values, you want to look for the character0
and not the integer.Also, according to WPCS, you should be using strict comparisons
===
or!==
I don’t see any use of your other parameters
url
etc in this code, but I assume this is just to understand the issue with the icon param?This is the source code for
shortcode_atts()
.Its logic states that it filters the keys in the
$atts
array by the whitelist of keys in your hardcoded array AND if any of the whitelisted keys are not found in$atts
, then they will be added to the output array with its hardcoded default value. Any elements with keys not mentioned in the hardcoded whitelist array will be excluded from the returned$out
array.All values passed in from the parsed shortcode string will be strings, so you can treat them as such when making conditions/comparisons.
To ensure that the
icon
value defaults to present the Font Awesome icon, set the hardcoded default value to1
.To avoid hard-to-read concatenation, use
sprintf()
with placeholders; this will make future maintenance easier too.I’ll use loose/truthy comparisons to determine if values should be included in the returned output string.