WordPress shortcodes: if-else statement

Posted on: 2014-12-05 | Categories: PHP

wordpress shortcodes 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:

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.

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: