- Navigate to the WordPress plugin directory of your development installation.
- Create a new directory called ch2-private-item-text.
- Navigate to this directory and create a new text file called ch2-private-item-text.php.
- Open the new file in a code editor and add an appropriate header at the top of the plugin file, naming the plugin Chapter 2 - Private Item Text.
- Add the following line of code to declare a new shortcode and specify the name of the function that should be called when the shortcode is found in posts or pages:
add_shortcode( 'private', 'ch2pit_private_shortcode' );
- Add the following code section to provide an implementation for the 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 access ';
$output .= 'this content.</div>';
return $output;
}
}
- Save and close the plugin file.
- Log in to the administration page of your development WordPress installation.
- Click on Plugins in the left-hand navigation menu.
- Activate your new plugin.
- Create a new post and wrap some of the content with the [private] and [/private] tags:
- Save and view the post to see that the text is visible while you are logged in to your site.
- Log out and refresh the page to see that the enclosed text has been replaced by a general message.