Skip to content

Instantly share code, notes, and snippets.

@dkjensen
Created June 20, 2024 20:55
Show Gist options
  • Save dkjensen/18625efdb2c990cc487f7aae0d1f4a33 to your computer and use it in GitHub Desktop.
Save dkjensen/18625efdb2c990cc487f7aae0d1f4a33 to your computer and use it in GitHub Desktop.
Prevent hidden WooCommerce products from showing search results / prevent purchase
<?php
/**
* Add a noindex, follow robots meta tag to hidden products.
*
* @param string $robots The robots meta tag.
* @return string
*/
add_filter(
'wpseo_robots',
function ( $robots ) {
if ( ! is_singular( 'product' ) || ! function_exists( 'wc_get_product' ) ) {
return $robots;
}
$product = wc_get_product();
if ( ! $product ) {
return $robots;
}
if ( 'hidden' !== $product->get_catalog_visibility() ) {
return $robots;
}
return 'noindex, follow';
}
);
/**
* Remove the add to cart button for hidden products.
*
* @param bool $purchasable Whether the product is purchasable.
* @param WC_Product $product The product object.
* @return bool
*/
add_filter(
'woocommerce_is_purchasable',
function ( $purchasable, $product ) {
if ( 'hidden' === $product->get_catalog_visibility() && ! current_user_can( 'manage_woocommerce' ) ) {
return false;
}
return $purchasable;
},
10,
2
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment