Home Business & Other WordPress 5 Cookbook

WordPress 5 Cookbook

By Rakhitha Nimesh Ratnayake
books-svg-icon Book
eBook $26.99 $17.99
Print $38.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $26.99 $17.99
Print $38.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Customizing Theme Design and Layout
About 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.
Publication date:
March 2020
Publisher
Packt
Pages
660
ISBN
9781838986506

 

Customizing Theme Design and Layout

The WordPress theme is the core feature behind what we see on the frontend of the site. The theme contains a collection of standard templates as well as theme-specific templates to manage the frontend screens. This chapter focuses on using standard theme features as well as creating custom features through child themes and custom templates. The standard theme features include customizers, menus, and built-in theme options. After reading this chapter, you will no longer be restricted to the default functionality of a theme. You will gain the skills to change the basic elements of a site using a customizer as well as create and use various custom templates in order to handle advanced requirements. Also, you will learn how to keep the customizations independent from your theme to keep them compatible with version upgrades.

In this chapter, we will learn about the following topics:

  • Using the theme customizer
  • Working with custom CSS in live preview
  • Using a custom page as a home page
  • Creating a child theme
  • Styling navigation menus
  • Creating conditional navigation menus
  • Adding a video header to the theme
  • Using conditional tags to control content display
  • Creating page templates from scratch
  • Creating a custom posts list template
  • Creating a custom 404 error page
 

Technical requirements

 

Using the theme customizer

The theme customizer is a WordPress feature that allows you to change certain theme settings and preview them on-site in real time. The built-in customizer is enabled on all themes with a basic set of configuration options. We can use the customizer API to add our own controls and settings to customize the theme. Many themes come with additional tabs and controls for advanced customizations.

In this recipe, we are going to look at the use of default theme customization settings.

Getting ready

Special preparation is not required for this recipe. The necessary features are available on the WordPress dashboard. We will be using the Twenty Twenty theme throughout this recipe.

How to do it...

Follow these steps to load the customizer, before we go through the different sections:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click on the Appearance menu.
  3. Click on the Customize option. You will get a screen similar to the following with the available customizer options for the theme:

The Twenty Twenty theme provides support for nine tabs, starting with the Site Identity tab. We are going to look at six of the nine tabs common for most themes.

Site Identity tab

Let's take a look at the use of the settings in the Site Identity tab:

  1. Click the Site Identity tab to get a screen similar to the following:
  1. Then, change site title and tagline to your preferred values.
  2. Click Select site icon and upload an image. The image's width and height should be equal. The minimum allowed size is 512 px.
  3. Click the Publish button to save the changes.

You will see the title and tagline change instantly on the right-hand side of the window. Also, once the icon has uploaded, it will show as the icon of the browser tab.

Colors tab

Let's take a look at the use of the settings in the Colors Identity tab:

  1. Click the Colors tab to get a screen similar to the following:
  1. Change Primary Color to Custom.
  2. Select a color from the color bar.
  3. Click the Publish button to save the changes.

You will see the colors for buttons, links, and featured image change on the site preview. This should be used when you want a different color scheme.

Menus tab

Let's take a look at the use of the settings in the Menus tab:

  1. Click the Menus tab to get a screen similar to the following:
  1. Click on the Create New Menu button to create a menu:
  1. Add a menu name as Main Menu and menu location as Desktop Horizontal Menu and click the Next button. The Twenty Twenty theme provides five built-in menu locations.
  2. Click the Add Items button to add menu items to the menu from the available list on the right-hand pane. Also, we can tick the Automatically add new top-level pages to this menu setting to add main pages to the menu without selecting them manually:
  1. Select the Pages, Posts, Categories, Tags, or Custom Post Type items for the menu. In this case, we are going to add the Home and Privacy Policy pages to the menu.
  2. Click the Publish button to save the changes.

You can go back to the Menus tab and see the newly created menu. This screen can be used to create new menus, edit existing menus, change the location of the menus, and view available menu locations with the current selection.

Widgets tab

Let's take a look at the use of the settings in the Widgets tab:

  1. Click the Widgets tab to load the widget areas of the theme as shown in the following screenshot:
  1. Click Footer #1 tab to load the widget area
  2. Click the Add Widget button to add a widget. Once you've done this, you'll see a screen similar to the following:
  1. Select a widget from the screen that opens on the right-hand side. The widget will be added to the existing list.
  1. Click the arrow icon of any widget to edit the settings. You will get a screen similar to the following for the Recent Posts widget:
  1. Change the necessary settings of the selected widget.
  2. Click the Remove button inside each widget to remove unnecessary widgets.
  3. Click the Reorder button to enable up/down arrows for each widget.
  4. Change the widget order by using the up/down arrows.
  5. Click Done to complete reordering.
  6. Click the Publish button to save the changes.

The Twenty Twenty theme provides two widget areas. This screen can be used to completely modify widgets in any given widget area.

Homepage Settings tab

Let's take a look at the use of the settings in Homepage Settings:

  1. Click the Homepage Settings tab.
  2. Click the A static page option. You will see the following screen:
  1. Select a page for the Homepage setting. If you don't have a page, click the Add New Page button and create a page. In this case, we will be creating a new page called Home.
  2. Select a page for the Posts page setting. If you don't have a page, click the Add New Page button and create a page. In this case, we will be creating a new page called Blog.
  3. Click the Publish button to save the changes.

This screen is used to configure the pages that will be used as home and blog pages. More details about this feature will be discussed in the Using a static page as a home page recipe.

The last tab is called Additional CSS. It will be discussed in detail in the next recipe, that is, Working with Custom CSS in live preview.

With this, we have checked the basic usage of the main five tabs in the theme customizer.

How it works...

The default Customizer tabs are enabled for any theme. However, some themes might remove these tabs and use custom tabs that have been generated by the theme. We have the ability to add custom tabs and settings to the customizer using Customizer API functions. The default settings available in the customizer are saved in the wp_options table of the WordPress database.

If you are not familiar with working with a WordPress database, please refer to the Appendix of this book for instructions on how to work with databases for these recipes.

All the settings changes are temporary until we click the Publish button. The changes in the settings are previewed instantly in the site window on the right-hand side. The preview process is handled by enqueuing necessary details and styles with JavaScript. Since the changes are previewed instantly, many people will think the changes have been saved. However, you will lose the changes when refreshing the page if you don't click the Publish button.

Usually, we modify the settings and check how they are changed in the layout on the right-hand side. However, we have the option of clicking the Edit button icons on the right-hand side to load the respective settings for that section. The use of Edit buttons makes this process simpler. We should use the customizer to modify the content and check the existing theme, as well as check multiple themes without activating each theme on the site.

 

Working with Custom CSS in live preview

We discussed the theme customizer in the previous recipe. Adding custom CSS is part of the new theme customizer. Using this new feature can save us bundles of time compared to saving changes in CSS files and loading the site again to view the changes in styles.

In this recipe, we are going to look at the process of adding theme styles with the customizer and checking the changes instantly with preview features.

Getting ready

Special preparation is not required for this recipe. The necessary features are available on the WordPress dashboard.

How to do it...

We are going to add some simple CSS changes to the headers and the page body to see the custom CSS in action. To do this, follow these steps:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click on the Appearance menu.
  1. Click the Customize option.
  2. Click the Additional CSS tab to see the following screen. The default instructions will be displayed for use. You can click the Close link after reading the instructions:
  1. Open the browser inspection tools and find the CSS class for the site title by right-clicking on the site and clicking the inspection tool on your browser. The following screenshot shows the CSS class using the inspection tool of the Chrome browser:
  1. Add the following CSS code to the Additional CSS section to style the title of the site:
.site-title{ background: red; padding : 5px;}

This style change will be shown immediately in the header.

  1. Click the Publish button to save the changes.

Now, if you visit the home page, you will see the style changes. Similarly, we can visit any page/post and use the customizer to add dynamic CSS for specific posts/pages.

How it works...

The Additional CSS tab is provided by default in the latest WordPress versions so that we can modify the CSS dynamically without using a third-party plugin. First, we add the following line of CSS code:

.site-title{ background: red; padding : 5px;}

This is a built-in CSS class that's used for the header of the site. We have modified it to change the background color to red with a 5px padding. Once the CSS has been added, customizer functionality enqueues the changes instantly and previews the change in real time on the site.

Once we click the Publish button, the CSS we added in this section will be stored in the wp_posts database table with a post type called custom_css. post_titile will contain the name of the theme while post_content will be the CSS we added in this field.

The Additional CSS section is specific to each theme. Once you change the theme, the Additional CSS section will be empty, until you save the custom CSS for that theme. This feature is a theme-specific setting. However, when we switch back to another theme, the styles that were saved for that theme will be retrieved from the database and applied to the site.

We can use this process to define and store dynamic CSS that's needed for each and every theme.

Once you've executed this recipe and tested the output, remove the CSS in the Additional CSS section and save the settings. We're doing this as we want to proceed with the original theme in the upcoming recipes.
 

Using a custom page as a home page

The default WordPress home page consists of a list of blog posts on the site. The content for the home page is generated within WordPress and is not visible as a post or page in the dashboard. Most sites will require a unique home page that describes the site, rather than a set of blog posts. So, we need the option of changing the default behavior.

The main settings section of WordPress allows us to customize the default behavior and define a custom home page. In this recipe, we are going to look at the process of changing the home page from the default blog post list to a custom page.

Getting ready

We need to have a custom static page as the home page of the site. Follow these steps to create a new page:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click the Pages menu.
  3. Click the Add New button to create a page.
  4. Add a title of Home and add Home Page as content.
  5. Click the Publish button to create the page.

This will create a new empty page that will be used as the home page of the site.

How to do it...

The process of changing the home page and customizing the blog page is a straightforward task. Follow these steps to configure the home page:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click the Settings menu.
  1. Click the Reading option. You will get a screen similar to the following called Reading Settings:

We'll be using the Your homepage displays setting for this process. The Your latest posts option will be selected by default to show the blog posts on the home page.

  1. Select the A static page (select below) option.
  2. Select the page we created in the Getting ready section as the home page.
  3. Select another page for the Posts page option and use it as the blog posts page.
  4. Click the Save Changes button.

Now, visit the home page of the site by clicking on the site title. You will see the new page we created in the Getting ready section with the content as Home Page. Also, you can go to the Pages list and click on the page we used for the Posts page setting to view the list of blog posts.

We have changed the home page successfully and used a custom page. Now, you can add home page content that's specific to your site by modifying the custom page we created in the Getting ready section.

How it works...

The setting for displaying the front page is stored in the wp_options table in the database with a key called show_on_front. The default value is posts. Therefore, the blog post list will be shown on the front page. Once we select and save the A static page (select below) option, the value of show_on_front will change to page.

Next, the Homepage and Posts page options will be saved in the wp_options database table with the page_on_front and page_for_posts keys. Once pages have been selected for these settings, the page_on_front and page_for_posts keys will hold the respective page IDs. The default value will be 0 for these settings.

Once the user request is sent for the front page, WordPress will use page_on_front to load the respective page as the home page. Also, when the blog post page is clicked, WordPress will check if the requested page is defined in the page_for_posts setting. Once a match has been found, it will display the list of blog posts.

There's more...

Once we select a page to be used for the posts page, WordPress will override the content of that page with the blog post list. The content of the page won't be visible anywhere on the frontend of the site.

Also, we may choose the same page for both the Homepage and Posts page settings by mistake. In such a case, a warning message will be displayed. If we continue using the same page without considering the warning, WordPress will load the blog posts list as the front page.

 

Creating a child theme

A child theme is basically a subversion of a WordPress theme. We can use a child theme to override the styles, templates, and functionality of a given theme without breaking the changes on theme upgrades. The functionality of a child theme can range from minor style changes to complete template changes. It's important to create a child theme for each and every theme we use to make and track changes.

In this recipe, we are going to look at the process of creating a simple child theme.

Getting ready

Open the code editor and make sure that you have access to the theme files in your local or external WordPress installation. We will be using the Twenty Twenty theme as the parent theme for creating the child theme.

How to do it...

Follow these steps to create a child theme for the Twenty Twenty theme:

  1. Open the wp-content/themes folder of your WordPress installation and create a new folder called twentytwentychild.
  2. Create a new file called style.css inside the twentytwentychild folder.
  3. Open the style.css file, add the following code to define it as a theme, and save the file:
/*
Theme Name: Twenty Twenty Child
Theme URL:
Description: Twenty Twenty ChildTheme
Author: John Doe
Author URL:
Template: twentytwenty
Version: 1.0.0
Text Domain: twentytwenty-child
*/
  1. Create a new file called functions.php inside the twentytwentychild folder.
  1. Add the following code to the functions.php file in order to include the stylesheet of the parent theme and save the file:
<?php
add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );
function enqueue_parent_styles() {
wp_enqueue_style( 'parent-style',
get_template_directory_uri().'/style.css' );
}
?>
  1. Log in to the WordPress Dashboard as an administrator.
  2. Click the Appearance menu.
  3. Click the Themes option. Now, your theme will appear in the list, as shown in the following screenshot:
  1. Click the Activate button to activate the theme.

Now, you can visit the home page of the site and the child theme will be displayed. However, you will not see any differences compared to the Twenty Twenty theme as we didn't change any styles or templates.

How it works...

The themes are loaded from the wp-content/themes folder. WordPress will look for style.css files inside the themes folder with the predefined comments we added in step 3. Once we add the style.css file with predefined comments inside the twentytwentychild folder, it will show up in the themes list in the Appearance | Themes section. Let's take a look at the code in step 3 and identify how it works.

First, we have to define the Theme Name and Theme URL. We need to use a unique name for the Theme Name option, whereas the Theme URL is an optional external URL that contains details of the theme. Then, we have the description and author information. These fields are also optional, so we can decide to add them or keep them blank.

Next, we have to define the Template field (which is a mandatory field when identifying a child theme). This should be the folder name of the parent theme. Then, we have the Version and Text Domain fields. We can define the theme version for the Version field and a unique slug for the Text Domain field, which will be used for translations.

After adding this comment in style.css, the theme will start showing on the theme list. However, the site will display without any styles, even after activating the theme at this stage. So, we need to include the style.css file of the parent by using the code in step 5. This code enqueues the style.css file of the parent theme when loading the site.

Now, the site will start displaying the styles of the parent theme. At this stage, there is no difference in the design or functionality of the child theme compared to the parent theme.

There's more...

In this recipe, we created a child theme for the Twenty Twenty theme. However, no functionality is provided by the child theme at this stage. We can use a child theme to add custom styles and change the functionality of a parent theme. In this section, we are going to look at the process of adding custom styles with a child theme.

First, we have to add the necessary styles to the style.css file of our child theme inside the twentytwentychild folder. Let's use the following CSS to change the color of the theme header:

#site-header {
background: #21c7d8;
}

Now, you can check the home page of the site. At this stage, the style change we made is not visible on the site header. The reason for this is that we only included the parent theme's style.css file in the functions.php file of the child theme. First, remove the existing code in functions.php file. Then, include the child theme's style.css file along with the parent theme's CSS file by adding the following code to the functions.php file:

add_action( 'wp_enqueue_scripts', 'wpccp_chapter2_enqueue_parent_styles' );
function wpccp_chapter2_enqueue_parent_styles() {
wp_enqueue_style( 'parent-style',
get_template_directory_uri().'/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' )
);
}

We already used the first wp_enqueue_style function to include the parent theme styles. The parent-style key can be changed to any unique name. The next line enqueues the child theme's style.css file with a dependency on parent theme styles. The get_template_directory_uri and get_stylesheet_directory_uri functions load the main theme directory and child theme directory paths. Now, you can visit the site and the changes in the header styles will be visible with the color we added.

If you aren't seeing the background color we added to the CSS file of the child theme, make sure to clear the browser cache and refresh the browser multiple times.

Before moving into the next recipe, remove or comment the CSS code added in the style.css file of the child theme.
 

Styling navigation menus

Simplified and clear navigation menus make the site more accessible to the user. The menu should be designed to let the user visit the most important parts of the site with a single click and let the user know what they are viewing at any given moment. WordPress generates a simple list-based menu by default. We can use the theme to modify the menu functionality and create stylish menus.

In this recipe, we are going to look at the process of changing the existing menu design using custom styles for menus.

Getting ready

We need to create a navigation menu before we get started with styling. Follow these steps to create a navigation menu for the Twenty Twenty child theme:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click the Appearance menu.
  3. Click the Menus option. You will see the following screen:
  1. Click the create a new menu link.
  2. Add a menu name of Primary Menu and click the Create Menu button.
  3. Select some menu items from the left-hand panel and click Add to Menu.
  4. Click the Save menu button.

Now, we have created a menu that can be used for custom styling.

How to do it...

We have created a basic menu for the Twenty Twenty theme. In this recipe, we are going to style each menu item using custom classes. To do this, follow these steps:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click on the Appearance menu.
  3. Click on the Menu option. You will see a screen similar to the following showing the menu we created in the Getting ready section of this recipe:
  1. Click the Screen Options menu at the top to view the enabled/disabled settings for the menu section. You will see the following screen:
  1. Click the CSS Classes option if it's not selected in your menu section. This will enable the CSS Class setting for each menu item.
  2. Click the down arrow of one of the menu items to open the menu item and its settings. The following screenshot shows a menu item's settings with the CSS Classes option enabled:
  1. Add a custom name(s) for the CSS class(es) to this menu item. We can add multiple classes by separating them with spaces. In this case, we have to add a class called wpc-home-menu-item. The class names that we added in this section will be used later in CSS files to add styles.
  2. Click the Save Menu button to save the settings.
  3. Click the Manage Locations tab to get to the following screen:
  1. Set the Primary Menu we created in the Getting ready section to Desktop Horizontal Menu.
  2. Click the Save Changes button.
  3. Open wp-content/themes/twentytwentychild/style.css with a text or code editor.
  4. Add the following CSS styles at the end of the file to customize the styles of the home menu item:
.wpc-home-menu-item{
background: #1862a2;
padding: 5px;
border: 1px solid;
}
.wpc-home-menu-item a{
color : #fff !important;
}
  1. Save the file.

Now, you can visit the home page of the site to see the modified menu item. In this case, we have changed the default styles of the home menu item. The following screenshot shows the home menu item with custom styling:

Usually, menu item styling is done to highlight specific menu items among others. We can use this kind of menu item-specific style for calls to action buttons or links to external sites.

We can follow this process for each menu item and add custom styles of our choice using custom CSS classes.

How it works...

Once we define CSS classes using the CSS Classes option in the menu item, it will be added to the <li> element of each menu item, along with the built-in CSS classes. You can check the applied CSS classes by using the browser inspection tool on the menu item. The modified menu item code will look something similar to the following:

<li id="menu-item-12" class=" wpc-home-menu-item menu-item menu-item-type-post_type menu-item-object-page menu-item-12 is-focused"><a href="http://www.yoursite.com/home/">Home</a></li>

As you can see, the element contains the wpc-home-menu-item class, followed by built-in CSS classes such as menu-item and menu-item-post_type. Then, we need to add the CSS code from Step 13 to the style.css file of the theme.

We used custom CSS to highlight the home menu item with a background color, padding, and a border. Also, we changed the color of the menu link to #000 to match the background color of the menu item.

Once styles for this class have been added to the style.css file of the theme, the changes will be shown on the menu. So, the menu item will be highlighted among the other menu items. We can also use the same class on multiple or all menu items to style a set of menu items differently from others.

There's more...

In this recipe, we looked at the process of using our own CSS on menu items to customize the styles of the default menu. However, we have the option of using existing menu plugins to completely customize and build a stylish menu without writing a single line of code. Let's take a look at how we can use an existing plugin to completely change the styles and effects of the entire menu:

  1. Go to the Plugins | Add New section from the Dashboard
  2. Search for Max Mega Menu in the Search Plugins field
  3. Install and activate the plugin
  4. Click Appearance | Menus. Here, you will see a new settings section alongside the menu for Max Mega Menu, as shown in the following screenshot:
  1. Click the Enable checkbox
  2. Change the events and settings based on your preference
  3. Hover over any menu item and click the Mega Menu button
  4. Click the icon tab and select an icon
  5. Follow steps 7 and 8 for each menu item
  6. Click the Save Menu button

Now, you can visit the home page of the site to see the modified menu that was generated by the Max Mega Menu plugin. You will see a stylish menu similar to the following with menu icons, animations, and a professional design:

We can use such plugins to easily convert the entire menu design or design of specific menu items.

Before moving on to the next recipe, remove the custom CSS for the home menu item we added in the style.css file of the child theme and deactivate the Max Mega Menu plugin.
 

Creating conditional navigation menus

We discussed the importance of navigation menus in the previous recipe. The items in the navigation menu are also important in modern sites due to the dynamic nature of their content. Modern sites like to involve users in site functionality rather than providing static content. A high percentage of sites provide different content for different users or user types. So, the menu is no longer a static one. We need to load user-specific menu items or menus to allow access only to the content for each user or user type.

In this recipe, we are going to create multiple navigation menus and display them conditionally based on the user role.

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...

We have to create multiple navigation menus. Follow these steps to create menus before loading them conditionally inside the theme:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click the Appearance menu.
  3. Click the Menus option.
  4. Click the create a new menu link.
  5. Add a unique name to the menu. In this case, we're using WPCookbookMenu1.
  6. Click the Create Menu button.
  7. Add items to the menu from Posts, Pages, Custom Links, and Categories by selecting them and clicking the Add to Menu button, as shown in the following screenshot:
  1. Click the Save Menu button to save the menu.
  2. Follow the same process from steps 4 to 7 and create two menus with different menu items and menu names.

Now, you should have three menus listed inside the Select a menu to edit drop-down field. Follow these steps to display the menus conditionally to different user roles:

  1. Go to the twentytwenty theme folder using the file manager and copy header.php file
  2. Go to twentytwentychildtheme folder and paste the header.php file
  3. Open the wp-content/themes/twentytwentychild/header.php file with your code editor.
  4. Find the following code block, which is used for displaying the default menu:
wp_nav_menu(
array(
'container' => '',
'items_wrap' => '%3$s',
'theme_location' => 'primary' ) );
  1. Replace it with the following code to dynamically load the menu based on user types:
$roles_menus = array('subscriber' => 'WPCookbookMenu1', 'administrator' => 'WPCookbookMenu2') ;
$menu_name = 'WPCookbookMenu3';
foreach ($roles_menus as $key => $menu) {
if(current_user_can($key)){
$menu_name = $menu;
}
}

wp_nav_menu(
array(
'menu' => $menu_name,
'container' => '',
'items_wrap' => '%3$s',
'theme_location' => 'primary' ) );
  1. Save the changes to the file.

Now, you need to view the home page as an administrator or subscriber as a normal user. If you only have the admin user on the site, use the Users section in the backend to create a new user with the Subscribe role for testing. You will see different menus displayed for each of the three user types.

How it works...

We can create an unlimited number of menus in the WordPress menu section and assign them to different menu locations in the theme. In this scenario, we wanted to change the top menu for different user types and show different menu items. So, we created three menus called WPCookbookMenu1, WPCookbookMenu2, and WPCookbookMenu3.

The menu of the Twenty Twenty theme is loaded from the header.php template. So, we copied the template into the TwentyTwenty Child theme folder with the same path. Then, we removed the existing menu generation code and added custom code to include the conditional checks.

In the first part of the code, we created an array to store user roles and a menu name to display the respective user role. Next, we used a foreach loop to traverse through the array and check the permission level of the current user with the current_user_can function. Once a match was found, we changed $menu_name to a role-specific menu while keeping WPCookbookMenu3 as the default value for $menu_name. The last part of the code is the same as the original code in the Twenty Nineteen theme, except for the addition of the 'menu' => $menu_name parameter and the removal of the theme_location parameter from the wp_nav_menu function.

The menu name changes based on the user role, which is used to conditionally display the menu. When a matching user role is not found, it will display the WPCookbookMenu3 menu for guests and logged in users with other roles.

Before moving on to the next recipe, replace the header.php file inside the child theme folder with the original file from the Twenty Twenty theme. We're doing this since we want to use the original theme for the next recipe.
 

Adding a video header to the theme

The website header is one of the most important places where you can highlight the most important content and attract visitors to the site. Using header images to give users a visual overview of the site is a common feature in many sites. The use of videos is becoming a trend and taking over the use of normal images. Header videos can be effectively used to give a quick and detailed overview of your product or company, compared to static images.

The latest introduction of video headers in WordPress 4.7 simplifies the process of adding a video to the header section. This is a built-in feature that needs to be enabled through the theme.

In this recipe, we are going to add header video support and display a video in the header section of the site.

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 availability of the header videos feature depends on the theme. We are going to use the Twenty Twenty Child theme for this recipe. The header video feature is not supported by default in the Twenty Twenty theme. Due to this, we have to add support to our child theme. Follow these steps to do so:

  1. Open the wp-content/themes/twentytwentychild/functions.php file with your code editor.
  2. Add the following lines of code to the end of the file to add support for a header video and save the file:
add_theme_support( 'custom-header', array(
'video' => true,
) );
  1. Log in to the WordPress Dashboard as an administrator.
  2. Click the Appearance menu.
  1. Click the Header option to open the Theme Customizer, as shown in the following screenshot:
  1. Click the Select video button to open the media uploader.
  2. Upload a .mp4 video from your computer.
  3. After uploading is completed, click the Choose Video button to add the video to the customizer.
  4. Also, use the Add new image button to upload an image for the header. This image will be displayed when there is a delay in displaying the video.
  1. Now, the header video will be shown in the Header Media section, as shown in the following screenshot. The image or video will not be visible in our child theme at this stage:

  1. Click Publish button to save the changes.
  2. Open the header.php file inside the child theme and find the following code, which is used for displaying the header of the site:
<div class="header-titles">
<!-- Step 13 code should be placed in the next line -->

<?php
// Site title or logo.
twentytwenty_site_logo();
// Site description.
twentytwenty_site_description();
?>
</div><!-- .header-titles -->
  1. Add the following code after the comment "Step 13 code should be placed in the next line". This code is used to add the HTML for the header video:
 <div class="custom-header-media">
<?php the_custom_header_markup(); ?>
</div>
  1. Open the style.css file of the child theme and add the following code at the end of the file. The code is used to display the header video with proper positioning:
.wp-custom-header video,
.wp-custom-header img,
.wp-custom-header iframe {
position: fixed;
height: 300px !important;
width: auto;
}

@supports ( object-fit: cover ) {
.wp-custom-header video,
.wp-custom-header img,
.wp-custom-header iframe {
height: 300px !important;
left: 0;
top: 0;
-o-object-fit: cover;
object-fit: cover;
width: 100%;
}
}
  1. Save the changes and refresh the customizer Header Media section.

Now, you will see the uploaded video in the header section of our child theme. The video will play automatically when the page is loaded.

How it works...

The header video feature is disabled by default. We have to enable it using the theme. Some themes provide built-in support for video headers, while other themes require manual configuration to enable video headers. The Twenty Twenty theme we are using throughout this chapter doesn't have built-in support for header videos. So, we have to enable header videos by adding the following code to the functions.php file:

add_theme_support( 'custom-header', array(
'video' => true,
) );

We can pass the custom-header parameter to the add_theme_support function to enable custom headers in a customizer. This can be either an image or a video header. We enable video support by passing video => true as a parameter. Once this code is added, your theme will display the header section in the customizer with the ability to upload both images and videos.

At this stage, we can upload a video. However, it's not visible on the theme as the Twenty Twenty theme doesn't support header videos. Then, we added the following code to the header.php file of the theme to enable the header video content inside the theme:

<div class="custom-header-media">
<?php the_custom_header_markup(); ?>
</div>

This function outputs the HTML elements that are needed to display the video in the header. At this stage, the video will be visible on the theme. However, the design would look unpleasant as the video would be displayed in one section of the header.

Due to this, we added the CSS code in step 14 to the style.css file of the theme to align the video and display it across the whole header. Once you refresh the browser, the video will be displayed in the header and start playing immediately. We can adjust the CSS as needed for our requirements and design.

Before you move on to the next recipe, remove the header video and remove the custom CSS we used for the header video in the style.css file.
 

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.
 

Creating page templates from scratch

We use templates to keep the site design separate from the logic and reuse it on multiple pages without duplicating the code. WordPress page templates is a feature that allows us to create custom templates and reuse them across multiple pages of the site. These page templates are used effectively in most premium themes to provide designs for common pages that are needed for a site. The knowledge of creating templates is useful for making even minor changes to the default template.

In this recipe, we are going to create a basic page template from scratch using custom coding.

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...

We can create a page template to use products in a site. Usually, a product landing page is different to a normal page and has different headers and footers. Let's create the product page template. Follow these steps:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click the Pages menu.
  3. Click the Add New button.
  4. Go to Page Attributes section on the right hand column.
  5. Click dropdown field for Template setting to get a screen similar to following:
  1. Open the wp-content/themes/twentytwentychild folder using a file manager.
  2. Create a new template called product.php.
  3. Add the following code to the product.php file to define the template as a WordPress Page Template:
<?php /* Template Name: Product Landing Page */ ?>
  1. Save the changes.
  2. Add the following code to the product.php file to display product information:
<?php get_header(); ?>
<section id="primary" class="content-area">
<h2>Product Page</h2>
<main id="main" class="site-main">
<?php
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/content', get_post_type() );
endwhile;
?>
</main><!-- #main -->
</section><!-- #primary -->
<?php get_footer();
  1. Click the Pages menu.
  2. Click the Add New button. You will be taken to the following screen:

As you can see, the settings section now contains a new setting called Template, under Page Attributes.

  1. Add a title and content for the page and select Product Landing Page as the Template.
  2. Click the Publish button to create the page.

Now, we can view this page on the frontend. We will see that the custom page template is used instead of the default template.

How it works...

We don't have any page templates by default in our child theme. This means that the Template setting on the pages screen is not enabled until we create a template. WordPress uses the Template Name value in the comments section to identify the page templates:

<?php /* Template Name: Product Landing Page */ ?>

Once a comment with Template Name is added, WordPress will consider that file as a page template. The name of the template is the value we define after the Template Name key.

In step 7, we added the elements for the product template. Here, we used a copy of the default page.php template with minor modifications. We removed the comments section and added a new header called Product Page.

Next, we used this template while creating pages using the Template field on the post edit screen. Once the page is saved, the page template name will be stored in the wp_postmeta table with a key called _wp_page_template. The value of this key will be product.php in this case. Once the user requests this page, WordPress will look for the settings to check if the page template is enabled and load the custom template instead of the default one.

 

Creating a custom posts list template

The default blog page shows all the posts on your site using the standard design of the theme. Sometimes, we want to display a set of selected posts inside a page as a grid with a customized design to promote them. We can use shortcode inside a page or create a page template to provide this functionality.

In this recipe, we are going to create a page template that will display a list of posts in a grid-based design.

Getting ready

Open the code editor and make sure you have access to the theme files in your local or external WordPress installation. Also, you need to add featured images to a few of the existing posts in order to see the complete design of Post Grid in action.

How to do it...

Follow these steps to create a custom page template that will display a list of posts as a grid:

  1. Open the wp-content/themes/twentytwentychild folder using a file manager.
  2. Create a new template called post-grid.php.
  3. Add the following code to the post-grid.php file, define it as a template, and save the changes:
<?php /* Template Name: Post Grid */ ?>
  1. Add the following code after the template name definition to load the header and retrieve the posts:
<?php
get_header();
$post_list = new WP_Query(array('post_type'=>'post',
'post_status'=>'publish', 'posts_per_page'=>-1));
?>
  1. Now, we can add the following template code after the code in step 4. This code will be used to display the posts list:

<?php if ( $post_list->have_posts() ) : ?>
<div id="list-post-panel">
<ul>
<?php while ( $post_list->have_posts() ) :
$post_list->the_post();
$image = get_the_post_thumbnail_url( get_the_ID()); ?>
<li>
<div class="post-list-featured-image"><img src="<?php
echo $image; ?>" /></div>
<div class="post-list-title"><a href="<?php
the_permalink(); ?>"><?php the_title(); ?></a></div>
</li>
<?php endwhile; ?>
</ul>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'There no posts to display.' ); ?></p>
<?php endif; ?>
</div>
<?php get_footer(); ?>
  1. Add the following styles to the style.css file of the Twenty Twenty child theme to display the post list as a grid:

#list-post-panel ul { width : 100%; list-style:none; }
#list-post-panel li{
width: 31%;
margin: 1%;
padding: 1%;
float: left;
background: #eee;
list-style: none;
text-align: center;
border: 1px solid #cfcfcf;
}

.post-list-featured-image img{
width: 100%;
height: 200px;
}
  1. Log in to the site as an administrator.
  2. Click the Posts menu,
  3. Click the Add New button to create a new post.
  1. Set the title for the post to Grid 1 and upload a featured image using the Set featured image button in the Featured image section:
  1. Click the Publish button to create the post.
  2. Follow steps 8 to 11 and create two more posts called Grid 2 and Grid 3.
  3. Click the Pages menu.
  4. Click the Add New button to create a new page.
  5. Add a title for the page and select Post Grid as the template under the Page Attributes | Template settings.
  6. Click the Publish button to create the page.

Now, you can view this page on the frontend. Here, you will see a grid-based post list, as shown in the following screenshot:

Here, we have a grid-based post list design with a three-column layout. This is a basic version of a modern grid template in order to keep up with the scope of this book.

If you are not getting a similar output, make sure that you clear your browser cache and refresh the page a few times to update the CSS and load the design. The output will vary, depending on the images you set as the featured images for the posts.

You can improve this design with animation effects and AJAX-based lazy loading.

How it works...

Let's identify how the template code works by using the following steps:

  1. First, we call the get_header function to include the default header for the template.
  2. Then, we add the Template Name: Post Grid comment to the post-grid.php file. Once this is added, it will be available for selection in the Page Attributes | Template setting section of the page edit screen, even without any template code.
  3. Next, we add the header and the query for retrieving posts. We did this in Step 5. In this scenario, we are loading all the published normal posts in the site.
  4. Then, we use the have_posts function on $post_list to check if any posts are being returned from the query. Once results are found, we traverse through the resultset using a while loop and add the post-related information inside an unordered list.
  1. We use the built -in get_the_post_thumbnail_url, the_permalink, and the_title functions to retrieve the featured post image URL, the link of the post, and the title.
  2. Next, we use the wp_reset_postdata function to restore the loop back to the main query of the post or page. Adding this function is essential to preventing conflicts in data loading in the main query after our secondary query has been executed.
This function should be invoked when we have a list of results from our query. Placing this outside the if statement may reset the main query, thus creating conflicts in the page.
  1. Next, we added the get_footer function to add the default footer and complete the page template.
  2. Finally, we added the CSS of the <ul> and <li> tags to make a grid type design with three columns. We used 31% as the width and float:left on the <li> tag to divide the list into three columns. Then, we set width:100% and fixed the height to 200px to make it look similar on all the posts, regardless of the uploaded image size.

Now, you understand how the template code works.

There's more...

In this recipe, we loaded the list of all the normal posts in the site. This is a primary implementation of a post list template. In the real world, these templates are used for displaying custom post types or filtered sets of posts instead of all posts. Let's take a look at the scenarios where we can change the query to make the template much more flexible:

  • Displaying a custom post in a list template: We can modify the query to display a list of entries from a custom post type such as WooCommerce products by changingpost_type:
$post_list = new WP_Query(array('post_type'=>'product', 'post_status'=>'publish', 'posts_per_page'=>-1));
  • Displaying posts from a specific category: We can modify the query to display posts only from the category specified in the category_name parameter:
$post_list = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'category_name' => 'books', 'posts_per_page'=>-1));
  • Displaying posts with more than x number of comments: We can modify the query to display a list of posts that have more than 10 comments:
$post_list = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'comment_count' => array( 'value' => 10,   'compare' => '>=',    ), 'posts_per_page'=>-1));

The WP_Query class provides a large number of such query parameters, so the possibilities are endless. You can view all the available query parameters at https://developer.wordpress.org/reference/classes/wp_query/.

 

Creating a custom 404 error page

We get a 404 page not found error whenever the server is unable to provide the content for a requested URL. This might be due to the server being down, a mistyped URL, or because content has been removed from the site. WordPress provides a built-in 404 page with a very simple message called Nothing Found, along with a form to search the site.

Many websites use custom well-designed 404 pages to attract more visitors by converting the error into something useful. In this recipe, we are going to create a custom 404 page with custom content for our theme.

Getting ready

You should have the Twenty Twenty Child theme activated on your site. 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...

Follow these steps to create a custom 404 template for the child theme:

  1. Open the browser and type in a non-existent URL for your site. If your site is www.yoursite.com, you can type in a random value such as www.yoursite.com/dewf687f6e8w to see the 404 page shown in the following screenshot:
  1. Go to wp-content/themes/twentytwenty and copy the 404.php file.
  2. Paste the file inside the wp-content/themes/twentytwentychild folder.
  3. Open the 404.php file in wp-content/themes/twentytwentychild folder. You will see the following code section:
<div class="intro-text"><p><?php _e( 'The page you were looking for could not be found. It might have been removed, renamed, or did not exist in the first place.', 'twentytwenty' ); ?></p></div>

<?php
get_search_form(
array(
'label' => __( '404 not found', 'twentytwenty' ),
)
);
?>
  1. We can customize this section to create a better looking 404 page with necessary information.
  1. Replace the message inside the intro-text<div> element, like so:
<div class="intro-text"><p><?php _e( 'The page you were looking for could not be found. It might have been removed, renamed, or did not exist in the first place.Maybe try a search or view our posts?', 'twentytwenty' ); ?></p></div>
  1. Next, copy the following code from the post-grid.php file we created in the previous recipe and add it after the intro-textdiv element to display a post grid inside the 404 template:
<?php 
$post_list = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'posts_per_page'=> 3 )); ?>

<?php if ( $post_list->have_posts() ) : ?>
<div id="list-post-panel">
<ul>
<?php while ( $post_list->have_posts() ) : $post_list->the_post();
$image = get_the_post_thumbnail_url( get_the_ID()); ?>
<li>
<div class="post-list-featured-image"><img src="<?php echo $image;
?>" /></div>
<div class="post-list-title"><a href="<?php the_permalink(); ?>"><?php the_title();
?></a></div>
</li>
<?php endwhile; ?>
</ul>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
</div>
  1. Save the content of the 404.php file.
  2. Visit the URL in step 1 again.

Now, you will see the modified 404.php page, as shown in the following screenshot:

As you can see, we have changed the message to ask the user to search the site or view available posts. So, the visitor will think about using these features and staying on the site without leaving after seeing the error.

How it works...

Once the user accesses an invalid URL, WordPress will look for a valid 404 template. The 404 template is generated by the 404.php file of the theme, so it will be a theme-specific page.

If a valid 404.php file is not available in the theme, WordPress will load the default 404 content within the core with a basic message and search form.

In this scenario, we have created a 404.php file in the child theme using the 404.php file of the parent theme. Now, WordPress will look for the 404.php file within the child theme, instead of the parent theme. In the custom 404 template, we removed the original header of the Twenty Twenty template and changed the message to the following:

<?php _e( 'The page you were looking for could not be found. It might have been removed, renamed, or did not exist in the first place.Maybe try a search or view our posts?', 'twentytwenty' ); ?>

Then, we used the code from the previous recipe to display the post list on a 404 page. However, the following code only limits the post list to three entries as this is a 404 page and too much information can discourage the user to browse the site:

<?php $post_list = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'posts_per_page'=> 3 )); ?>

The other parts of the code are exactly same as they are for the post-grid.php file.

There's more...

The purpose of designing a custom 404 page with additional content is to motivate the user to keep using the site when they feel frustrated after receiving an error. This error can be due to their mistakes in requesting an invalid URL or the requested content not being available at that time. In any case, we have to make sure to effectively use a 404 page to keep the users on our site. Modern sites are using creative designs and valuable content in 404 pages to attract users. Let's look at some of the things we can do in 404 page designs:

  • Inform the user about the error: We should add a message informing the users that an error has occurred and possible reasons for the error. Also, it's good practice to apologize, even with a simple Sorry statement.
  • Inform the user about the next step to take: Including a search form asking to search the site, providing links to commonly used parts of the site, or asking them to contact you can be valuable for the user to move forward and stay on the site.
  • Show a glimpse of the most important site content: This is actually an advantage for the site owner as they can provide the content that they want the user to see. This could be the most popular posts on a blog or popular products in a store.
  • Show something funny or creative: Regardless of whether a visitor requested an invalid URL or whether the site generated the error for the URL that existed previously, the visitor is going to be a bit annoyed. So, including a funny or creative video, image, or design can help change the mood of the visitor and motivate them to use the site.

You should use one or more of these techniques and build a productive 404 error page that helps the users as well as benefit you as the site owner.

About the Author
  • Rakhitha Nimesh Ratnayake

    Rakhitha Nimesh Ratnayake is a freelance web developer, writer, and open source enthusiast. He has over 9 years of experience in developing WordPress applications and plugins. He develops premium WordPress plugins for individual clients and the CodeCanyon marketplace. User Profiles Made Easy and WP Private Content Pro are the most popular plugins developed by him. Building Impressive Presentations with impress.js was his first book, which was published by Packt Publishing. He is also the author of the first three editions of WordPress Web Application Development. In his spare time, he likes to read books and spend time with his family

    Browse publications by this author
Latest Reviews (3 reviews total)
After working on WordPress sites for a couple of years, I was looking for an additional set of solutions to get more out of WordPress. Instead the book just covers basic concepts of WordPress, declared as receipies. So I get nearly no additional knowledge out of those aprox 650 pages. The book itself is not so bad, e.g. for beginners to dive in the word of WordPress. But the additional benefit for more experienced users is very much limited.
Good up to date content on a fast moving topic...
WordPress 5 Cookbook
Unlock this book and the full library FREE for 7 days
Start now