| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace RenzoJohnson\Blocks\WooCommerce; |
| 6 |
|
| 7 |
\defined( 'ABSPATH' ) || exit; |
| 8 |
|
| 9 |
/** Keeps WooCommerce transactional pages noindex in Yoast's robots output. */ |
| 10 |
final class RobotsGuard { |
| 11 |
|
| 12 |
public const OPTION_ENABLED = 'blocks_woo_robots_guard_enabled'; |
| 13 |
|
| 14 |
/** Mirrors the condition in WooCommerce's own wc_page_no_robots(). */ |
| 15 |
private const GUARDED_PAGES = array( 'cart', 'checkout', 'myaccount' ); |
| 16 |
|
| 17 |
public function __construct( private readonly \Blocks_Settings_Repository $settings ) { |
| 18 |
} |
| 19 |
|
| 20 |
public function register_hooks(): void { |
| 21 |
// Late, so a site's own robots customisation still wins if it runs later. |
| 22 |
\add_filter( 'wpseo_robots_array', $this->filter_yoast_robots( ... ), 20 ); |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* @param mixed $robots Yoast's assembled robots directives. |
| 27 |
* @return array<string, mixed> |
| 28 |
*/ |
| 29 |
public function filter_yoast_robots( $robots ): array { |
| 30 |
$robots = \is_array( $robots ) ? $robots : array(); |
| 31 |
|
| 32 |
if ( ! $this->is_active() ) { |
| 33 |
return $robots; |
| 34 |
} |
| 35 |
|
| 36 |
if ( isset( $robots['index'] ) && 'noindex' === $robots['index'] ) { |
| 37 |
return $robots; |
| 38 |
} |
| 39 |
|
| 40 |
if ( ! $this->is_guarded_page() ) { |
| 41 |
return $robots; |
| 42 |
} |
| 43 |
|
| 44 |
$robots['index'] = 'noindex'; |
| 45 |
|
| 46 |
// Preview hints do not apply to noindex URLs. |
| 47 |
unset( $robots['max-snippet'], $robots['max-image-preview'], $robots['max-video-preview'] ); |
| 48 |
|
| 49 |
return $robots; |
| 50 |
} |
| 51 |
|
| 52 |
private function is_guarded_page(): bool { |
| 53 |
if ( ! \is_page() ) { |
| 54 |
return false; |
| 55 |
} |
| 56 |
|
| 57 |
$current = (int) \get_queried_object_id(); |
| 58 |
|
| 59 |
return $current > 0 && \in_array( $current, WooPages::guarded_ids( self::GUARDED_PAGES ), true ); |
| 60 |
} |
| 61 |
|
| 62 |
private function is_active(): bool { |
| 63 |
if ( ! \function_exists( '\wc_get_page_id' ) || ! \defined( 'WPSEO_VERSION' ) ) { |
| 64 |
return false; |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Escape hatch for site owners who want Yoast's stock robots output. |
| 69 |
* |
| 70 |
* @param bool $enabled Whether the guard runs. |
| 71 |
*/ |
| 72 |
return (bool) \apply_filters( 'blocks_seo_woo_robots_enabled', $this->settings->get_bool( self::OPTION_ENABLED, false ) ); |
| 73 |
} |
| 74 |
} |
| 75 |
|