0

I'm trying to add a "noindex" tag for out of stock products.

When I import the product IDs with global $product;, the product page and homepage are white without any errors.

And when I import the product IDs with $product = wc_get_product( $post->ID );, only the homepage is white with no errors.

I am trying the same codes with another hook and they are working fine. How else can I get the product IDs for the add_action(wp_head) hook to work smoothly?

// Add noindex tag for out of stock product
add_action ( 'wp_head', 'add_tagseo_headmeta', 1 );
function add_tagseo_headmeta() {
    
        global $post;
        $product = wc_get_product( $post->ID );

        // For simple product
        $stock_quantity = get_post_meta($post->ID, '_stock', true);
        if( $stock_quantity < 1 && $product->is_type('simple')  ) {
    
           echo '<meta name="robots" content="noindex">';
        } 
       
       // For variation product
       $total = 0;
       if ( $product->is_type( 'variable' ) ) {
        foreach ( $product->get_visible_children() as $variationId ) {
            $variation = wc_get_product( $variationId );
            $total += $variation->get_stock_quantity();
        }  
        
       if ( $total < 1 ) {

           echo '<meta name="robots" content="noindex">';
        }
    }
}
ersezar
  • 57
  • 6
  • Don't assume that product is just available, certainly not with a hook that runs on all pages. Use `global $product;` and then `if ( is_a( $product, 'WC_Product' ) ) { //Continue..` – 7uc1f3r Jul 10 '22 at 14:33
  • Instead of `global $product` I used `if ( get_post_type( get_the_ID() ) == 'product' ) { $product = new WC_Product(get_the_ID() );` and it works fine now. I couldn't figure out what the difference is from 'global $product'. – ersezar Jul 10 '22 at 16:04

0 Answers0