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:
- First, add the code to your theme’s functions.php file.
- Use the add_filter() function to hook into the sq_post filter of the Squirrly SEO plugin.
- In the filter function, check if the current post is a product and if the wc_get_product() function exists.
- Get the product object from the WooCommerce plugin using wc_get_product() function.
- Check if the product exists and has the is_in_stock() method.
- 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.
- 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.
0 Comments