Conditional Content by Post/Page with WordPress Shortcodes

This is an easy introduction to adding conditional content to WordPress posts and widgets using custom shortcodes — without a plugin.

Useful for custom html and text widgets; define widget content per post.

Conditional WordPress Shortcodes

In the below shortcode examples; text content will be included or excluded depending on a specific post/page or a group of posts/pages. You can place these [shortcodes] anywhere within your WordPress site/blog contents.

Everything is customized within the functions.php file with the theme editor. Just add the relevant code to the bottom of the file with your edits.

Please note that shortcodes do not work within the text/html widget by default — you will first need to add these two lines to functions.php to allow it:

add_filter( 'widget_text', 'shortcode_unautop' );
add_filter( 'widget_text', 'do_shortcode' );

Creating a Custom Shortcode

This is the basic code that creates a shortcode without conditions:

function customshortcode_function() {
 return 'this shortcode just displays this text, nothing else';
}

add_shortcode('customshortcode', 'customshortcode_function');

Just replace all instances of “customshortcode” with the desired name.

To use it on any widget, post or page add this anywhere within your content:

[customshortcode]

Creating a Conditional Shortcode

Next I’ll show a few useful examples using the WordPress Conditional Tags — there are a lot of them however so possibilities are endless.

Show text content depending on post slug:

function specificpost_function() {
if (is_single('conditional-content-in-wordpress-with-simple-shortcodes')) {
 return 'This text will only show on a post with a specific slug';
}
}

Show text content depending on page slug:

function specificpage_function() {
if (is_page('conditional-content-in-wordpress-with-simple-shortcodes')) {
 return 'This text will only show on a page with a specific slug';
}
}

Show text content depending on multiple post slugs:

function multipleposts_function() {
if (is_single(array('first-post', 'second-post', 'third-post'))) {
 return 'This text will only show on a group of posts with a specified slug';
}
}

Exclude text content on multiple page slugs:

function excludepages_function() {
if (!is_page(array('first-post', 'second-post', 'third-post'))) {
 return 'This text will be excluded on specified page slugs and included on all other pages';
}
}

And so on.. it’s easy without a plugin.

More ideas what you can do with shortcodes and content?
Please, let us know in the comments!

Twitter Button Facebook Button Google Button LinkedIn Button

Leave a Reply

Your email address will not be published. Required fields are marked *