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">';
}
}
}