Skip to contentSkip to main navigation Skip to footer

Optimize Your Sitemap with Squirrly SEO: Create a Custom Hook to Exclude Out-of-Stock Products and Add Noindex

To create a custom hook for Squirrly SEO plugin to exclude a product from sitemap and add noindex if the product is out of stock, you can follow these steps:

  1. First, add the code to your theme’s functions.php file.
  2. Use the add_filter() function to hook into the sq_post filter of the Squirrly SEO plugin.
  3. In the filter function, check if the current post is a product and if the wc_get_product() function exists.
  4. Get the product object from the WooCommerce plugin using wc_get_product() function.
  5. Check if the product exists and has the is_in_stock() method.
  6. If the product is out of stock, set the $post->sq->noindex, $post->sq->nofollow, and $post->sq->do_sitemap properties to true and false, respectively.
  7. Return the modified post object.

Here is the modified code:

add_filter('sq_post', function ($post){

   //If the current post is a product
   if ($post->post_type == 'product' && function_exists('wc_get_product')) {

      //get the product from woocommerce
      $product = wc_get_product( $post->ID );

      //If the product exists and has the property is_in_stock
      if ($product && method_exists($product, 'is_in_stock')) {

         //if the product is out of stock
         if(!$product->is_in_stock()){
            //exclude the product from Squirrly sitemap
            $post->sq->noindex = true;
            $post->sq->nofollow = true;
            $post->sq->do_sitemap = false;
         }

      }
   }
   
   return $post;
}, PHP_INT_MAX, 1);

This code will hook into the sq_post filter and modify the post object based on the product’s stock status. If the product is out of stock, the code will set the noindex, nofollow, and do_sitemap properties of the Squirrly SEO plugin to exclude the product from the sitemap and add noindex to the page.

Was This Article Helpful?

0 Comments

There are no comments yet

Leave a comment