WordPress shortcodes: if-else statement
Posted on: 2014-12-05 | Categories:
PHP
Lately developing Level7 WordPress plugin I needed simple solution that will allow non-technical users to create conditional statements in content of pages or posts. It had to be something very simple, intuitive and with support for WordPress Conditional Tags or any other callables.
What is callable? Callable is a function or class method that can be called.
WordPress shortcodes to the rescue
Let’s imagine sample registration page – we should display different content to authenticated and non-authenticated users. All we need in such a scenario is code like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
<!-- wordpress page or post content --> [if is_user_logged_in] You are already logged in. Please use the menu to select proper option. [else] Display registration form. [form] [/if] <!-- or just --> [if is_user_logged_in] You are already logged in. Please use the menu to select proper option. [/if] <!-- or --> [if has_post_thumbnail 123] <img src="..." > [/if] |
How to achieve it? We need to create function that will handle if-esle statement and register it as WP shortcode.
What is a shortcode? It is a WordPress-specific block of code that allows users to embed special features (inside post or page content) or to modify content – sometimes using just one line of code. More information can be found in documentation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
<?php function if_statement($atts, $content) { if (empty($atts)) return ''; $callable = array_shift($atts); if (is_callable($callable)) { $condition = (boolean)call_user_func_array($callable, $atts); } else { throw new Excaption('First argument must be callable!'); } $else = '[else]'; if (strpos($content, $else) !== false) { list($if, $else) = explode($else, $content, 2); } else { $if = $content; $else = ""; } return do_shortcode($condition ? $if : $else); } // register shortcode add_shortcode('if', 'if_statement'); |
This can also be a part of some class.
Notice: With this shortcode implementation: if-else
statement cannot be nested.
We can also create our own callables (functions or class methods) and use it in if-selse
statement:
|
function has_products_in_cart() { // some code } function is_order_confirmation_page() { // some code } |
|
[if has_products_in_cart] Preview cart or continue shipping [/if] [if is_order_confirmation_page] include some extra conversion code [/if] |
Hammad
December 29, 2014 18:59
Something really new for me, is it supported for all WordPress themes? I’m using genesis.
Kamil
December 30, 2014 10:44
It’s not supported in core. You can add such a shortcode to your theme or plugin.
Cheers.
Nyle M.
March 16, 2016 05:59
What if we want to put a shortcode within a short code?
[if is_logged_in]
[if something]__[else]__[/if]
[/if]
Any ideas?