WordPress, the leading content management system (CMS) globally, possesses a remarkable market share of over 60%.
One of the primary reasons for its widespread adoption is the extensive support community and the abundance of freely available plugins. These factors contribute significantly to WordPress’s dominance in the market.
Nevertheless, the utilization of plugins comes with certain drawbacks.
In many instances, plugins can negatively impact your website’s Core Web Vitals scores. For instance, they might load unnecessary CSS or JavaScript files on every page, causing performance degradation.
To address this issue, there are a few possible solutions. You can hire a programmer to handle it for you, purchase a premium plugin, or embark on a learning journey to tackle the problem independently.
Alternatively, you can adopt a hybrid approach by combining custom coding for certain aspects and relying on plugins for others.
The purpose of this article is to assist you along your learning path, specifically by exploring essential WordPress hooks that can enhance your website’s technical SEO.
What’s WordPress Hook?
WordPress hooks are essential elements within WordPress that enable developers to enhance the capabilities of the content management system (CMS) without having to alter the core files of WordPress itself. This feature simplifies the process of updating themes or plugins, as it prevents any interference with customized modifications.
These hooks offer developers a robust mechanism to expand the functionality of WordPress and implement personalized modifications to their websites.
What’s Filter Hook?
The hook filter function serves to alter the function’s output before it is presented. One practical application is to append your blog name to page titles by utilizing the wp_title filter hook.
What’s Action Hook?
Action hooks provide programmers with the ability to execute specific actions at particular stages during the execution of WordPress Core, plugins, or themes. These actions can include events like the publication of a post or the loading of JS and CSS files.
By familiarizing yourself with a few fundamental action hooks or filters, you can accomplish a variety of tasks without having to rely on hiring developers.
The following hooks will be covered in this article:
- wp_enqueue_scripts
- wp_head
- script_loader_tag
- template_redirect
- wp_headers
wp_enqueue_scripts
The following code snippet serves as an effective method to prevent unnecessary loading of CSS or JS files on specific pages, thereby avoiding redundancy.
An instance of this is observed in the widely used Contact Form 7 plugin, with an impressive installation count of over 5 million. By default, this plugin loads CSS and JS files on every page, even though they are only required on the contact page.
To exclude the CSS and JS files associated with Contact Form 7 from loading on pages other than the contact page, you can use the provided code snippet.
function my_dequeue_script(){ //check if page slug isn't our contact page, alternatively, you can use is_page(25) with page ID, or if it is a post page is_single('my-post') if ( !is_page('contact') ) { wp_dequeue_script('google-recaptcha'); wp_dequeue_script('wpcf7-recaptcha'); wp_dequeue_script('contact-form-7'); wp_dequeue_style('contact-form-7'); } } add_action('wp_enqueue_scripts', 'my_dequeue_script', 99 );
Here are some important considerations when modifying the action hook in your code:
- The action hook priority should be set to 99 to ensure that your modification is executed last in the queue. This ensures that it takes precedence over other actions.
- Avoid setting the priority to a lower value like 10, as it won’t work as intended. This is because the CF7 enqueue function already uses priority 20. To guarantee that your modification takes effect, choose a priority value significantly higher than the default one.
- When implementing the code, we utilized “contact-form-7” as a function argument identifier. You might be curious about how to discover this identifier.
- Fortunately, it’s a straightforward and intuitive process. Simply use the inspect element tool available in your browser and check for the “id” attribute of link or script tags. This will help you identify the relevant function argument.
You can check your website source code using inspect element and start dequeuing any JS or CSS file where they are not needed.
wp_head
The purpose of this action hook is to include various resources such as JS, CSS files, or meta tags in the <head> section of a webpage.
By utilizing this hook, you have the ability to load important resources that appear above the fold in the head section. This can have a positive impact on the Largest Contentful Paint (LCP) scores, which measure the loading performance of a webpage.
For instance, Google recommends preloading fonts, as well as preloading logos and featured images on article pages, since these elements always appear above the fold. Preloading them can significantly enhance the LCP.
To achieve this, you can use the following code snippet:
function my_preload() { ?> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preload" as="style" href="https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,200..900;1,200..900&family=Lora:ital,wght@0,400..700;1,400..700&display=swap"/> <link rel="preload" as="image" href="https://www.yoursite.com/path-to-logo/image.jpg"/> <?php if( has_post_thumbnail() ): // check if article has featured image?> <!-- Featured Image --> <?php // $featured_image = str_ireplace(array( '.png', '.jpg', '.jpeg'), '.webp', $featured_image ); // enable this if you have webp images. ?> <?php $featured_image = get_the_post_thumbnail_url( get_the_ID(), 'full' ); ?> <link rel="preload" as="image" href="<?php echo $featured_image;?>"/> <?php endif; } add_action('wp_head', 'my_preload', 3 );
To optimize the loading speed of your website, there are specific steps you can take. Firstly, you can preload Google fonts by including the necessary code in the first two lines. After that, it is advisable to preload your site’s logo. Additionally, it’s important to check if the article being loaded contains a featured image, and if so, preload that image as well.
Furthermore, it’s worth mentioning that your theme or website might have webp image support enabled. If that’s the case, it is recommended to preload the webp versions of the images instead. This will further enhance the overall loading performance of your website.
script_loader_tag
You must be familiar with the concept of render-blocking resources, which can be resolved by utilizing defer or async attributes while loading JavaScript tags. This optimization is crucial for enhancing FCP and LCP performance metrics.
To achieve async or defer loading of your theme or plugin’s JS/CSS files, you can effectively employ a filter action. This action facilitates filtering the HTML output of the script tags, ensuring the desired async or defer loading behavior for your assets.
function my_defer_async_load( $tag, $handle ) { // async loading scripts handles go here as an array $async_handles = array('wpcf7-recaptcha', 'another-plugin-script'); // defer loading scripts handles go here as an array $defer_handles = array('contact-form-7', 'any-theme-script'); if( in_array( $handle, $async_handles) ){ return str_replace( ' src', ' async src', $tag ); } if( in_array( $handle, $defer_handles ) ){ return str_replace( ' src', ' defer="defer" src', $tag ); } return $tag; } add_filter('script_loader_tag', 'my_defer_async_load', 10, 2);
The filter has two parameters: an HTML tag and a script handle, both of which were mentioned earlier while inspecting the element.
The script handle can be utilized to determine whether to load the script asynchronously or defer its loading.
Once you have loaded the script with either the defer or async attribute, it’s essential to verify for any JavaScript errors using the browser console. If you encounter any errors, it might be necessary to seek assistance from a developer, as resolving them may not be a simple task.
template_redirect
This action hook is triggered prior to determining the appropriate template to load. It provides an opportunity to modify the HTTP status code of the response.
To illustrate, you might encounter unsolicited backlinks leading to your internal search query pages, which may contain unusual characters or frequently occurring patterns.
wp_headers
This action hook is used to modify HTTP headers of WordPress.
You can use this hook to add security headers to your website response HTTP headers.
function my_headers(){ $headers['content-security-policy'] = 'upgrade-insecure-requests'; $headers['strict-transport-security'] = 'max-age=31536000; preload'; $headers['X-Content-Type-Options'] = 'nosniff'; $headers['X-XSS-Protection'] = '1; mode=block'; $headers['x-frame-options'] = 'SAMEORIGIN'; $headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'; $headers['Link'] = '<https://www.yoursite.com/wp-content/uploads/themes/yourtheme/images/logo.jpg>; rel=preload; as=image'; $headers['Link'] = '<https://fonts.gstatic.com>; rel=preconnect; crossorigin'; $headers['Link'] = '</wp-content/uploads/themes/yourtheme/images/logo.webp>; rel=preload; as=image'; return $headers; } add_filter( 'wp_headers', 'my_headers', 100 );
In addition to security headers, you have the option to include “Link” tags, allowing you to pre-connect or preload resources. This serves as an alternative approach to preloading, as mentioned earlier. Furthermore, you can customize your HTTP headers by adding “X-Robots-Tag” directives according to your specific requirements.
Conclusion
Plugins are commonly developed to address diverse tasks and may not always cater to your specific requirements.
One of the remarkable features of WordPress is its inherent flexibility, allowing you to modify its core effortlessly using just a few lines of code.
In our conversation, we explored action hooks that can enhance technical SEO. However, WordPress offers an extensive range of action hooks that you can delve into and utilize to accomplish virtually any customization you desire, minimizing your reliance on plugins.