-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

WordPress Plugin Development Cookbook
By :

A different type of shortcode that exists in WordPress is one that encloses content in posts and pages. Using a syntax similar to HTML tags, enclosing shortcodes can be used to identify parts of an item's content that need to be treated in a special way. For example, it is possible to use this type of shortcode to style a part of the post.
As an example of how to create enclosing shortcodes, this recipe shows you how to create a set of tags that will identify part of a post or page that should only be shown to visitors that are logged in to a site. In this way, the shortcode acts similarly to a filter hook, with the added bonus that you do not need to parse for instances of these tags in your code, as would normally be done in a filter callback.
Follow these steps to create a new enclosing shortcode to identify private parts of website content:
plugins
directory of your development installation.ch2-private-item-text
.ch2-private-item-text.php
.Chapter 2 - Private Item Text
.add_shortcode( 'private', 'ch2pit_private_shortcode' );
ch2pit_private_shortcode
function:function ch2pit_private_shortcode( $atts, $content = null ) { if ( is_user_logged_in() ) { return '<div class="private">' . $content . '</div>'; } else { $output = '<div class="register">'; $output .= 'You need to become a member to '; $output .= 'access this content.</div>'; return $output; } }
[private]
and [/private]
tags:Figure 2.12 – Using the private enclosing shortcode
Similar to a filter function, enclosing shortcodes receive a copy of the text that has been wrapped with new tags through the $content
parameter. It is then possible to return this text with additional HTML code, or completely replace it with new content. In this specific case, we used the is_user_logged_in
WordPress function to determine whether the current visitor is logged in to the site. Based on the result of that query, the code determines whether the original content should be displayed with some additional div
tags, or whether the visitor should see a message encouraging them to join the website to see this content.