Book Image

WordPress 5 Cookbook

By : Rakhitha Nimesh Ratnayake
4 (1)
Book Image

WordPress 5 Cookbook

4 (1)
By: Rakhitha Nimesh Ratnayake

Overview of this book

WordPress has been the most popular content management system (CMS) for many years and is now powering over 30% of all websites globally. With the demand for WordPress development and skilled developers ever-increasing, now is the best time to learn WordPress inside out. This book starts with simple recipes for configuring WordPress and managing basic platform features. You’ll then move on to explore how to install and customize WordPress plugins, widgets, and themes. The next few chapters cover recipes for content and user-management-related topics such as customizing the content display, working with content types, using the new Gutenberg editor, and customizing editorial workflow for building advanced blogs. As you advance, you’ll learn how to use WordPress as an application framework as well as a platform for building e-commerce sites. This WordPress book will also help you optimize your site to maximize visibility on search engines, add interactivity, and build a user community to make the site profitable. Finally, you’ll learn how to maintain a WordPress site smoothly while taking precautions against possible security threats. By the end of the book, you’ll have the tools and skills required to build and maintain modern WordPress websites with the latest technologies and be able to find quick solutions to common WordPress problems.
Table of Contents (16 chapters)

Using conditional tags to control content display

We've already discussed the importance of conditional menus to give access to conditional content. The user or user type is not the only factor that differentiates content. WordPress websites can display content based on specific dates, browsers, specific posts/page types, specific settings, and so on. This conditional content is handled by the conditional tags of WordPress. Conditional tags are a set of built-in functions that return Boolean values after checking various conditions that are specific to WordPress sites.

In this recipe, we are going to look at the use of some of the available conditional tags and tips for using them in the real world.

Getting ready

Open the code editor and make sure you have access to the theme files in your local or external WordPress installation.

How to do it...

The use of conditional tags varies, based on your requirements. So, in this recipe, we are going to consider three examples of using conditional tags in a real-world environment.

Displaying conditional content on the archive and single posts

Follow these steps to conditionally load different content for posts in different scenarios:

  1. Open the wp-content/themes folder of your WordPress installation and open the functions.php file of Twenty Twenty child theme.
  2. Add the following code at the end of the functions.php file to change the content for single and archive pages:
function wpccp_chapter2_conditional_content($content) {
if( is_single() ){
$content .= "<p>Additional Content for single post </p>";
}else if( is_archive() ){
$content .= "<p>Archive Page Content for each post </p>";
}
return $content;
}
add_filter('the_content', 'wpccp_chapter2_conditional_content');
  1. Save the changes.
  2. Visit one of the posts on the site using your web browser. You will get a screen similar to the following showing your post title and content:
  1. Visit the blog list page of the site. We configured the blog page using the Your homepage displays | Posts page setting in the Using a static page as a home page recipe.

Now, you will see the difference in content for the same post in a single post page as well as a post list page due to the conditional tags we used.

Displaying content for guests and members

Follow these steps to conditionally load different content for guests and members:

  1. Open the wp-content/themes folder of your WordPress installation and open the functions.php file.
  2. Add the following code at the end of the functions.php file to change the content based on user type:
function wpccp_chapter2_conditional_user_content($content) {
if( is_user_logged_in() ){
$content .= "<p>Additional Content for members </p>";
}
return $content;
}
add_filter('the_content', 'wpccp_chapter2_conditional_user_content');
  1. Save the changes.
  2. Visit one of the posts on the site using your web browser as a guest user.
  3. Log in to the site using the details of an existing user account.
  4. Visit the same post we used in step 3 of this recipe.

Now, you will see additional content for the members (logged in users) inside posts and pages.

Using multiple conditional tags

Follow these steps to understand how to use multiple conditional tags to display a specific page for only members of the site:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click the Pages menu.
  3. Click the Add New option.
  4. Create a new page with content that's private to members and save the page.
  5. Get the page ID from the browser URL. The last part of the URL will look like post.php?post=2&action=edit.
  6. Open the wp-content/themes folder of your WordPress installation and open the functions.php file of Twenty Twenty child theme.
  7. Add the following code at the end of the functions.php file to apply restrictions on the specified page and redirect unauthorized users. We've used 2 as the ID of the page. Feel free to replace it with the ID of the page you want to restrict:
function wpccp_chapter2_validate_page_restrictions(){
global $wp_query;
if (! isset($wp_query->post->ID) ) {
return;
}

if(is_page('2') && ! is_user_logged_in() ){
$url = site_url();
wp_redirect($url);
exit;
}
}
add_action('template_redirect', 'wpccp_chapter2_validate_page_restrictions');
  1. Save the changes.
  2. Visit the page we created in step 4 while being logged in as an administrator.
  3. Log out from the site.
  4. Visit the same page we created in step 4 as a guest user.

Now, you will see the page as any logged-in user. However, you will be redirected to the home page URL once you view the same page as a guest user.

How it works...

The conditional tag in WordPress verifies a given condition and returns a Boolean value. We can execute different operations based on the Boolean value that's the result of one or more conditional tags. Let's take a look at how each example works.

Displaying conditional content on the archive and single posts

In this scenario, we used WordPress' the_content filter. This filter is used to pass the content of posts and pages and make the necessary modifications. We can add this filter to the functions.php file of the theme to change its content based on different conditions. Consider the following lines:

if( is_single() ){
$content .= "<p>Additional Content for single post </p>";
}else if( is_archive() ){
$content .= "<p>Archive Page Content for each post </p>";
}

Let's assume we want to show additional content on a detailed post page and hide it on archive pages. Usually, this is used to let users get more content by visiting the detailed post instead of just looking at archive page content for each post and leaving the site. We can check if a detailed post has been loaded using the is_single conditional tag. This function will return true for a detailed post or custom post type pages. Once the condition matches, we add more content to the existing content by using PHP .= operators.

The existing content will be automatically passed to this function. This content could be the original content of the post or the content that was modified by other plugins.

In the next section, we check if a list page of posts or custom post types is loaded using the is_archive function. Once matched, we add different content. This could be content informing the user about additional content in the detailed page and asking them to visit that page. These two conditional tags give the user different content based on the loaded template type.

Displaying content for guests and members

Similar to the previous scenario, we used the the_content filter. However, this time, we used it for a different purpose: showing user-specific content instead of template-specific content. Consider the following code inside the the_content filter:

if( is_user_logged_in() ){
$content .= "<p>Additional Content for members </p>";
}

In this case, we used the is_user_logged_in conditional tag to check whether the user is logged into the site or accessing the site as a guest. If the function returns success, we display the member-specific content.

Using multiple conditional tags

So far, we used a single conditional tag in each of the previous scenarios. Now, let's take a look at the use of multiple conditional tags at once to narrow the filtering. In this case, we will be creating a private page and redirecting the users who don't have access to that page. Consider the following code:

function wpccp_chapter2_validate_page_restrictions(){
global $wp_query;
if (! isset($wp_query->post->ID) ) {
return;
}

if(is_page('2') && ! is_user_logged_in() ){
$url = site_url();
wp_redirect($url);
exit;
}
}
add_action('template_redirect', 'wpccp_chapter2_validate_page_restrictions');

In this case, we use an action called template_redirect, instead of a filter like last time. This is a built-in action that runs just before loading a template for each request. We can use this to check conditions and make necessary redirections.

More about actions and filters will be covered in Chapter 3, Using Plugins and Widgets, in the Customizing WordPress plugins recipe.

First, we define the global $wp_query variable and use it to check if a post or page has been loaded by the current request by checking $wp_query->post->ID. The code will only continue for requests that render a post or page. Then, we use two conditional tags in the next if statement. In the first condition, we check for a specific page load by passing the page ID to the is_page function. In this case, we have used the Page with 2 as the ID. Next, we use the is_user_logged_in function with the ! operator to see if the user is logged in or not. Once the code has been placed, only logged in users who access the page with the ID 2 will be able to see the content of this page. Other users will be redirected to the path defined inside the site_url function. In this case, we are redirecting to the home page of the site. We used the && operator to combine two conditional tags. Similarly, you can use multiple && or || operators to check unlimited numbers of conditions using conditional tags.

There's more...

In this recipe, we learned how to use WordPress conditional tags using three different examples. However, we only covered a small percentage of a large list of conditional pages. The use of each conditional tag is similar to the examples we used in this recipe. Therefore, we are not going to discuss all the available tags. You can find out more about available conditional tags and how to use them at https://codex.wordpress.org/Conditional_Tags.

The use of these conditional tags is straightforward. However, incorrect use of these can create conflicts in your site. In this section, we are going to look at what you should be considering when using conditional tags in general and when using certain conditional tags:

  • Using conditional tags in the wrong place: WordPress loads conditional tags after the posts_selection action. Therefore, you can only use these functions in actions that have been loaded after that specific action. The posts_selection action is already executed before reaching the the_content filter or the template_redirect action. Therefore, our code worked without issues. However, if we included the conditional tags directly inside functions.php without any action or filter, the tags will not work as expected.
  • Using conditional tags without proper filtering: We have to pass the necessary parameters or use additional filtering in order to apply the conditions for intended content. In our example, we used the is_single tag to check the detailed page. However, this tag applies for both, all posts and all custom post types. So, if we intend this only for normal posts, there will be issues. Due to this, we need additional non-conditional tag checks to make sure the condition is only applied to the content we intend.
  • Using conditional tags for unintended functionality: Some of the tags are confusing and difficult to understand, unless we check the documentation. In such cases, we might be using them for different purposes than what's actually intended. The is_admin tag is intended for checking the admin screens of WordPress. However, the name suggests that we can use it to check admin permissions. Major issues will occur if we rely on this tag to provide admin permissions. Similarly, the is_home and is_front_page tags are also confusing as most people think that they're the same thing. However, is_home refers to the blog home page while is_front_page refers to the home page of the site. So, we should check the documentation to understand the intended functionality and use them wisely.

These techniques will help you use conditional tags effectively without creating conflicts regarding site functionality.

Before moving on to the next recipe, remove or comment out all the code we added for this recipe inside the functions.php file of the Twenty Twenty child theme.