Optimizing WordPress Header Tags: Boost Performance with ‘add_filter’ for Lighthouse Scores

Photo by Ales Nesetril
Photo by Ales Nesetril on Unsplash

Introduction

WordPress is a popular content management system that allows users to create and manage websites. Optimizing WordPress websites for performance is crucial in improving user experience and search engine rankings. One important aspect is minimizing render-blocking resources. These resources, often linked in the header, can significantly slow down a site’s loading speed. In this article, we’ll delve into using add_filter functions in WordPress, specifically “style_loader_tag” and “script_loader_tag”, to modify header tags for stylesheets and script links.

Understanding Render-Blocking Resources

When you test your site’s performance using tools like Lighthouse, you might encounter warnings related to “render-blocking resources”. These resources, typically CSS and JavaScript files loaded in the header, prevent the page from rendering until they are fully loaded. This delay affects the site’s performance and user experience.

Optimizing with add_filter

Fortunately, WordPress offers a powerful way to modify these tags without altering core files. By using the add_filter function with “style_loader_tag” and “script_loader_tag”, we can customize how these resources are loaded in the header.

Here’s an example of how you can use add_filter for modifying script tags:

// Defer JavaScript Loading
function add_defer_attribute($tag, $handle) {
    // Add handles of the scripts you want to defer
    $scripts_to_defer = ['script1', 'script2'];

    if (in_array($handle, $scripts_to_defer)) {
        return str_replace(' src', ' defer="defer" src', $tag);
    }

    return $tag;
}
// script_loader_tag: This filter allows you to modify the HTML output of JavaScript script links
add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);

In this example, add_defer_attribute function adds the defer attribute to specific scripts defined in the $scripts_to_defer array. This defers the loading of these scripts until after the page has been parsed.

Tip: To determine the handle of a script, add a comment to the end of the <script> tag with the handle value. e.g. return $tag . "<!-- πŸ‘† handle: $handle -->\n\n";. Check the source of the webpage or use the developer tools to find the handle value.

Tip: Use the is_admin() function to distinguish between client-facing and admin pages.

Similarly, to modify stylesheet links to remove unnecessary stylesheets, you can use:

// Remove Unnecessary Stylesheets
function remove_unused_styles($tag, $handle) {
    // Add handles of the stylesheets you want to remove
    $styles_to_remove = ['style1', 'style2'];

    if (in_array($handle, $styles_to_remove)) {
        return '';
    }

    return $tag;
}
// style_loader_tag: This filter allows you to modify the HTML output of CSS stylesheet links
add_filter('style_loader_tag', 'remove_unused_styles');

This code snippet illustrates how to remove specific stylesheets by checking their handles defined in the $styles_to_remove array.

Implementing Modifications

To apply these modifications:

  1. Navigate to your WordPress dashboard
  2. Go to “Appearance” and select “Theme File Editor”
  3. Choose the functions.php file from the list of theme files
  4. Insert the provided code snippets at the bottom of the functions.php file
  5. Save the changes

Conclusion

Using add_filter with “style_loader_tag” and “script_loader_tag” in WordPress allows for efficient modification of header tags without directly altering core files. By deferring scripts and removing unnecessary stylesheets, you can address render-blocking resource issues, significantly improving your site’s performance.

Remember, while these methods can enhance performance, exercise caution and always backup your files before making any changes. Optimizing WordPress headers through add_filter is a powerful way to address performance warnings and provide a better user experience without modifying core files.

Test the client-facing webpage and editor separately to ensure that all necessary scripts are loaded.

Share:

WordPress Shortcode by Example

Photo by Joshua Reddekopp
Photo by Joshua Reddekopp on Unsplash

Introduction

WordPress is one of the most popular content management systems, making it an excellent platform for creating websites and blogs. One powerful feature of WordPress is the ability to use shortcodes. Shortcodes allow you to easily add dynamic content or functionality to your website without writing complex code. In this article, we will explore what shortcodes are, how to create them, and provide practical examples of using shortcodes in WordPress.

What is a Shortcode?

In WordPress, shortcode is a powerful feature that allows you to add dynamic content or functionality to your website. When WordPress encounters a shortcode in a post or page, it replaces it with the corresponding output. For example, you can create a shortcode to display a contact form or to embed a YouTube video.

Creating a Simple Shortcode

To create a shortcode in WordPress, you need to define a function that generates the output for the shortcode. Let’s start with a basic example. Suppose you want to create a shortcode that displays a welcome message. Open your theme’s functions.php file (Appearance > Theme File Editor > Theme Functions) and add the following code:

function welcome_message_shortcode()
{
  return "Welcome to my website!";
}

add_shortcode( 'welcome', 'welcome_message_shortcode' );

In this example, we create a function called welcome_message_shortcode() that returns the desired welcome message. Then, we use the add_shortcode() function to register our shortcode. The first argument of add_shortcode() is the shortcode tag (in this case, ‘welcome’) and the second argument is the name of the function that generates the shortcode’s output.

Using Shortcodes in WordPress

Once you have defined a shortcode, you can easily use it in your posts, pages, or even in your theme files. To use the welcome shortcode from the previous example, simply insert [welcome] into your content. When WordPress encounters the shortcode, it will replace it with the output from the welcome_message_shortcode() function.
[welcome]

Shortcode Attributes/Parameters

Shortcodes can also accept attributes/parameters, which allow you to customize the output of the shortcode. Let’s extend our previous example to include an attribute that allows the user to specify their name. Update the welcome_message_shortcode() function as follows:

function welcome_message_shortcode( $atts = [] )
{
  $name = isset( $atts['name'] ) ? $atts['name'] : 'Guest';

  return "Welcome, $name!";
}

Here, we modify the function to retrieve the name attribute from the $atts array. If the attribute is not provided, we default to ‘Guest’. Now, you can use the welcome shortcode with the name attribute.

[welcome name="John"]

Enclosing Shortcodes

Enclosing content with a shortcode allows manipulations on the enclosed content.

function welcome_message_shortcode( $atts = [], $content = null )
{
  return $content;
}
[welcome]Welcome Friend![/welcome]

Specifying Defaults Using Function “shortcode_atts()”

function welcome_message_shortcode( $atts = [] )
{
  // Set default attribute values
  $defaults = [
      'greeting' => 'Welcome',
      'name' => 'Guest',
  ];

  // Merge user-defined attributes with default values
  $attributes = shortcode_atts( $defaults, $atts );

  // Use the attribute values in your shortcode output
  $output = "

{$attributes['greeting']}, {$attributes['name']}!

"; return $output; }

In this example, we define values for the attributes using an associative array $defaults. We then use the shortcode_atts() function to merge the user-defined attributes with the default values. This ensures that if a specific attribute is not provided by the user, it will fallback to the default value specified in the $defaults array.

Finally, we use the attribute values in the shortcode output, generating an HTML paragraph (<p>) with the specified greeting and name.

Tip: Attribute does not support camelCase variable, variable will be converted to lower case. For example: [shortcode myName='...'] becomes $atts['myname'].

Conclusion

WordPress shortcodes provide a convenient way to add dynamic content and functionality to your website. By creating and using shortcodes, you can save time and effort by reusing code snippets and generating dynamic output with ease.

Remember to always test your shortcodes and handle any potential errors or edge cases. With a little practice, you’ll be able to leverage the power of shortcodes to enhance your WordPress website.

Share:

How to Create a Privacy Page on WordPress – A Step-by-Step Guide

Introduction

Creating a privacy page on your WordPress website is not only essential for legal compliance but also a critical step in building trust with your audience. In this step-by-step guide, we’ll walk you through the process of creating a privacy page on WordPress. By the end of this tutorial, you’ll have a comprehensive privacy page that ensures transparency and data protection.

Step 1: Log in to Your WordPress Dashboard

Before you can create a privacy page, log in to your WordPress admin dashboard. You can access it by adding “/wp-admin” to your website’s URL and entering your login credentials.

Step 2: Navigate to “Settings”

Once logged in, navigate to the “Settings” option on the left sidebar and click on “Privacy”.

WordPress Privacy Setting Menu
WordPress Privacy Setting Menu

Step 3: Create or Select a Privacy Page

Under the Privacy settings, you’ll find an option to select a page for your privacy policy. If you have already created a privacy page, you can choose it from the drop-down menu. If not, you can create a new page by clicking the “Create New Page” button.

WordPress Privacy Page
WordPress Privacy Page

Step 4: Customize Your Privacy Page

After selecting or creating your privacy page, you can further customize it to meet your specific needs. It’s essential to provide comprehensive information about how your website collects, uses, and protects user data. Be transparent about cookies, analytics, and any third-party services you may use. You can find sample privacy policy templates online, but remember to tailor the content to your website’s practices.

Tip: Employ the is_page('Privacy Policy') function within template files, such as header.php or footer.php, to conditionally style a post or page. This can be especially valuable if you intend to exclude advertisements from the Privacy Policy page.

Step 5: Format Your Content for Readability

Make sure your privacy page is easy to read and navigate. Use headings, bullet points, and paragraphs to organize your content effectively. This not only enhances the user experience but also improves search engine optimization (SEO).

Step 6: Review and Publish

After completing your privacy page, review the content for accuracy and clarity. Make any necessary revisions. Once satisfied, click the “Publish” button to make your privacy page live on your website.

Step 7: Create a Privacy Policy Link

To ensure easy access, add a link to your privacy page in your website’s footer, menu (Appearance > Menus), or any other prominent location. This will help users find your privacy page effortlessly.

Congratulations! You’ve successfully created a privacy page on WordPress. Regularly review and update your privacy policy to stay compliant with evolving regulations and maintain user trust. Remember, transparency and user trust are vital components of a successful online venture.

Share:

WordPress migration from Arvixe to MochaHost

Below are some tips on migrating WordPress from one web host to another. My experience is with migrating from Arvixe to MochaHost, but the steps mentioned should be similar on other shared web hosting accounts.

Back up WordPress database

  • On cPanel, click on phpMyAdmin
  • Select the WordPress database, then Export
  • Select check boxΒ Custom – display all possible options
  • Make sure all tables are selected
  • Make sure check boxΒ Save output to a file is checked
  • Scroll to the bottom and click on Go
  • A .sql file will be produced, save it to your hard drive
WordPress database back up
WordPress database back up

Back up WordPress files

  • Connect via ftp to your web host
  • Copy all WordPress files to your local drive
  • If you are not sure where the WordPress files are located, access the WordPress icon in cPanel, click on Edit, the pencil icon, of your WordPress installation.
  • The Directory field shows where the WordPress files are located
WordPress File Location
WordPress File Location

Install a new WordPress instance on the new web host

Note: If this step is skipped and the files are copied to the new server directly, the backup feature of Softaculous will not be available.

  • On cPanel of the new web host, click on WordPress. This should be in the SOFTACULOUS APPS INSTALLER section.
  • Click on Install Now
  • Fill in the appropriate fields.
  • It is recommended to keep Table Prefix the same as the old database to avoid having to rename tables
  • Make a record of Database Name
WordPress Database Name and Table Prefix
WordPress Database Name and Table Prefix

Copy old WordPress files to new web host

  • Connect via ftp to your new web host
  • Rename the WordPress folder on new web host, e.g. public_html to public_html__backup
  • Create a folder with the same name as the WordPress folder before it was renamed, e.g. public_html
  • Copy WordPress files from the old web host to this folder

Set up WordPress database on new web host

  • On cPanel of the new web host, click on phpMyAdmin
  • Select the WordPress database, then Operations
  • Copy the database for backup and comparison purpose
  • Click on Import, select the .sql file created earlier, click Go to import the database

Configuration: wp-config.php

  • On cPanel of the new web host, click on File Manager
  • Select the WordPress folder, e.g. public_html
  • Open file wp-config.php
  • Change the following settings to match the new server, replace ??? with values from new web host (Note: values can be found from the wp-config.php file in the backup folder, e.g. public_html__backup)

That should be it, WordPress is now successfully transferred to the new web host.

Share:

Best way to modify WordPress theme

Do not modify the template files directly. If you update or upgrade the selected theme, all your changes will disappear.

Use child theme instead.

Step 1: Create a child theme folder

  1. Create a folder for the child theme in folder wp-content\themes\
  2. Name the child theme folder with suffix -child
  3. For example, if parent theme folder is twentysixteen, the child theme folder should be twentysixteen-child

Step 2: Create a style.css file

  1. Within the child theme folder, create style.css
  2. Copy the style sheet header below, customize it, and add it to the top of style.css

    Tip: The “Template” field must match the folder name of the parent theme

    Tip: The mandatory fields are “Theme Name” and “Template”, the rest is optional

  3. Add style rules below the header

Step 3: Create a functions.php file

  1. Within the child theme folder, create functions.php
  2. Copy the code below

Step 4: Activate the child theme

  1. Under Appearance > Themes, the new child theme should show up now

    Tip: Add screenshot.png in the child theme folder to display a thumbnail for the child theme

  2. Click “Activate” to start using the child theme

Modify other files such as header and footer

All files within the theme folder can be modified. Examples:

Header section: header.php

Footer section: footer.php

Single post content section: template-parts/content-single.php

Make a copy from the parent theme folder and save it into the child theme folder. If a file does not exist, the parent file will be used.

Share: