In WordPress shortcodes, how can I pass boolean attributes?
Both of [shortcode boolean_attribute="true"]
or [shortcode boolean_attribute=true]
are giving string values.
EDIT
There would be no problem for users who know what they’re doing if I use the trick which was commented by @brasofilo. But some users will get lost if they give an attribute false
value and receive true
value. So is there any other solution?
Is easy to use
0
and1
values and then typecasting inside the function:[shortcode boolean_attribute='1']
or[shortcode boolean_attribute='0']
but if you want you can also strictly check for
'false'
and assign it to boolean, in this way you can also use:[shortcode boolean_attribute='false']
or[shortcode boolean_attribute='true']
Then:
As an extension to @G.M. answer (which is the only possible way to do this), here’s a slightly shortened/beautified and and an extended version (which I personally prefer):
Shortened/Beautified variant
It’s enough to do a
boolean
check for the contained value. If it’strue
, the result will be(bool) true
, else it will be false. This produces a one casetrue
, everything elsefalse
result.Extended/User-safe variant
The reason why I prefer this version is that it allows the user to type in
on/yes/1
as an alias fortrue
. This reduces the chance for user errors when the user doesn’t remember what the actual value fortrue
was.Additional notes:
1) Always pass the 3rd argument for
shortcode_atts()
. Else the shortcode attributes filter is impossible to target.2) Never use
extract()
. Even core wants to reduce those calls. It’s equally worse toglobal
variables, as IDEs don’t stand a chance to resolve the extracted contents and will throw failure messages.Here a shorter simple version, building on gmazzap’s answer:
Use ‘1’ or ‘0’, then cast using a double bang “!!” which changes a “truthy/falsey” value to it’s boolean equivalent
note this will NOT work with “true” and “false” strings, only “1” and “0”