add_action( 'init', $this, 'add_rewrite_rule' ); $loader->add_filter( 'query_vars', $this, 'add_query_var' ); // Priority 5: same reasoning as ABDS_SEO_Sitemap_Controller's own // template_redirect hook -- core's redirect_canonical() runs at the // default priority (10) and would 301 this rewrite endpoint (which // core doesn't itself recognize) before this handler ever ran. $loader->add_action( 'template_redirect', $this, 'maybe_serve_key_file', 5 ); } /** * This site's IndexNow key, from abds_seo_settings.indexnow.key. * * @return string */ public static function key(): string { $settings = get_option( 'abds_seo_settings', array() ); return (string) ( $settings['indexnow']['key'] ?? '' ); } /** * The full public URL of the key file, e.g. https://example.com/{key}.txt. * * @return string */ public static function key_url(): string { $key = self::key(); return '' !== $key ? home_url( '/' . $key . '.txt' ) : ''; } /** * Registers the /{key}.txt rewrite rule. Existing sites need a rewrite- * rules flush to pick this up -- ABDS_SEO_Settings_Installer's v3 * backfill already does this once (see that class's own docblock), and * ABDS_SEO_Rewrite_Flush covers every later release that changes a * rewrite rule regardless of settings-version bumps. */ public function add_rewrite_rule(): void { $key = self::key(); if ( '' === $key ) { return; } add_rewrite_rule( '^' . preg_quote( $key, '/' ) . '\.txt$', 'index.php?' . self::QUERY_VAR . '=1', 'top' ); } /** * Whitelists the key-file query var so WordPress's rewrite parsing * doesn't strip it. * * @param array $vars Existing public query vars. * @return array */ public function add_query_var( array $vars ): array { $vars[] = self::QUERY_VAR; return $vars; } /** * Serves the key file's plain-text body when the rewrite rule matched. */ public function maybe_serve_key_file(): void { if ( '1' !== get_query_var( self::QUERY_VAR ) ) { return; } $key = self::key(); if ( '' === $key ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); return; } header( 'Content-Type: text/plain; charset=UTF-8' ); echo esc_html( $key ); exit; } }