in

How to use them to improve your SEO

popular wordpress hooks 63ee25f52f0ab sej

[ad_1]

WordPress is the world’s most popular Content Management System (CMS) with over 60% market share.

A large support community and dozens of free plugins available make it affordable to build a website with WordPress (WP). It also plays an important role in why it has such a large market share.

However, as you know, installing plugins comes at a cost.

In many cases, your Core Web Vitals score may drop. For example, you might load unwanted CSS or JS files on every page you don’t want.

To fix this, you’ll have to hire a programmer to do it for you, buy a premium plugin, or follow a small learning path and do it yourself.

You can even go hybrid, solving some parts of the problem with custom coding and others with plugins.

This article is intended to assist you on your learning path and covers the most necessary WordPress hooks to improve your website’s technical SEO.

What are WordPress hooks?

WordPress hooks are a key feature of WP that allow developers to extend the functionality of the CMS without modifying the core WP files. This allows you to easily update your themes and plugins without breaking your custom changes.

They provide a powerful way for developers to extend the functionality of WordPress and make custom changes to their site.

What is a filter hook?

Hook filter functions are used to modify the output of a function before it is returned. For example, you can use the wp_title filter hook to suffix your page title with your blog name.

What are action hooks?

Action hooks allow programmers to perform specific actions at certain points during the execution of WP Core, plugins or themes, such as when a post is published or when JS and CSS files are loaded .

By learning a few basic action hooks or filters, you can accomplish a wide range of tasks without hiring a developer.

Use the following hooks:

  • wp_enqueue_scripts
  • wp_head
  • script_loader_tag
  • template_redirect
  • wp_headers

wp_enqueue_scripts

This is exactly the action hook we use to prevent redundant CSS or JS files from loading on unwanted pages.

For example, the popular free Contact Form 7 plugin, which has been installed over 5 million times, loads CSS and JS files on every page, but should only be loaded where a contact form resides.

To exclude CF7 CSS and JS files on pages other than contact pages, you can use the code snippet below.

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 );

There are some important points. The action hook’s priority is set to 99 to ensure that changes are executed last in the queue.

For example, setting it to 10 will not work because the CF7 enqueue function uses a priority of 20. So set the priority high enough to run last and have an effect.

Also, in the code, I used “contact-form-7” as the argument identifier for the function. You may be wondering how I found it.

It’s very simple and intuitive. Use your browser’s inspector tool to check the id attribute of the link or script tag.

The id attribute of the script tagAuthor screenshot, February 2023

You can use the inspect element to inspect your website’s source code and start dequeuing unwanted JS or CSS files.

wp_head

This action hook attaches a resource JS, CSS file, or meta tag to a web page Used to add to a section.

This hook allows you to preload above-the-fold resources in the head section to improve your LCP score.

For example, one of Google’s recommendations for preloading fonts, and logos and featured images on article pages always load above-the-fold. To improve the LCP you should preload them.

To do so, use the code snippet below.

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 );

The first two lines are for preloading the Google fonts, then preloading the logo, checking if the article has a featured image, then preloading the featured image.

As an additional note, your theme or site may have webp images enabled. In that case you need to preload those webp versions.

script_loader_tag

We often hear about render-blocking resources that can be fixed by lazy or asynchronous loading of JavaScript tags. Important for improving FCP and LCP.

This filter action is used to filter the HTML output of script tags. This is exactly the filter you need to asynchronously or lazily load JS/CSS files in your theme or plugins.

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);

This filter takes two arguments, an HTML tag and a script handle.

You can use the handle to determine which script to load asynchronously or lazily.

Always check the browser console for JS errors after deferring or asynchronous loading. If you see JS errors, you may need developer help as they may not be easy to fix.

template_redirect

This action hook is called before deciding which template to load. This can be used to change the HTTP status code of the response.

For example, there may be spam backlinks to internal search query pages containing strange characters or common patterns.

At Search Engine Journal, we’re used to spammy backlinks pointing to internal search pages in Korean. From the server logs, I learned that Googlebot is crawling them intensively.

spam backlinksAuthor screenshot, February 2023

WordPress’ default response code is 404 not found , but we recommend throwing a 410 to tell Google that they’re gone for good.

function my_410_function(){
  if( is_search() ) {
    $kw = $_GET['s'];
    // check if the string contains Korean characters
    if (preg_match('/[\x{AC00}-\x{D7AF}]+/u', $kw)) {
     status_header(410, 'Not Found');
    }
  }// end of is_search
}
add_action( 'template_redirect', 'my_410_function', 10 );

In our case, we know that there is no Korean content, so we configured the conditions accordingly.

However, it may contain international content in Korean and may have different terms.

For non-programmers in general, ChatGPT is a great tool for generating conditions using regular expressions. This can be used to create if/else conditions based on spam patterns from GSC.

wp_headers

This action hook is used to modify HTTP headers in WordPress.

You can use this hook to add security headers to your website’s 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 can add (as many as you need) “link” tags to preconnect or preload any resource.

Essentially, this is an alternative to preloading as described above.

Optionally, you can also add “X-Robots-Tag” (as many as you want) to the HTTP header.

Conclusion

Plugins are often aimed at solving different tasks and are often not specifically designed to meet your specific needs.

The ability to easily modify the WordPress core is one of the most beautiful aspects of WordPress, and can be done with just a few lines of code.

We’ve talked about action hooks that you can use to improve your technical SEO, but WordPress comes with plugins that you can explore and use to do basically anything you need, with minimal use of plugins. There are a number of action hooks you can do.

Other resources:


Featured image: Grafico moze/Shutterstock



[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    HLpMSObMF7osePieIzXrcKU96Mf esn3G gOD jTIZc

    OPP officer guilty of sexual assault on unconscious woman and recording it to ‘teach her a lesson’

    Microsoftx27s Secret Dutch Data Center Business Shutterstock 2254993917

    These Angry Dutch Farmers Really Hate Microsoft