PluginProbe
Blocks – Reusable Content, Shortcodes & Site Variables / trunk
Blocks – Reusable Content, Shortcodes & Site Variables vtrunk
26.09.03.15 26.08.31.21 26.08.22.20 26.08.22.22 26.08.22.17 26.08.22.13 26.08.21.19 26.08.07.23 26.07.19.14 26.07.13.21 26.07.13.17 26.07.12.13 026.07.07.21 026.07.05.18 026.06.26.20 026.06.26.21 026.06.08.20 026.05.13.14 026.04.29.10 trunk 026.02.22.22 026.03.16.23 026.04.23.13
blocks / src / WooCommerce / RobotsGuard.php

RobotsGuard.php in Blocks – Reusable Content, Shortcodes & Site Variables trunk, at src/WooCommerce/RobotsGuard.php

75 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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