fallback covers WordPress versions * without the wp_robots API, and every newer-API integration * degrades gracefully). Branding moved to robotstxt.software * (Plugin URI / Author URI). * @since 3.1.5 Maintenance review: WordPress floor corrected to 4.7 (the * oldest tested version and the first with the complete REST * API); nonce verification in the form handlers split into a * capability check plus a standalone check_admin_referer(). * @since 3.1.6 Admin UI modernization: inline styles replaced with admin * color-scheme-aware, RTL-ready classes (audit M7); stale * form-handler wp_die() message corrected (I2); unreachable * REST fallbacks removed (I5). * @since 3.5.0 WooCommerce special-page contexts (Cart, Checkout, My * Account) detected through the page-ID options, and the * compatibility window narrowed to WordPress 7.0-7.2 and * PHP 8.3-8.6 (declared floors raised from 4.7 / 5.6). * @since 3.6.0 Modern robots directives (notranslate, max-snippet, * max-image-preview, max-video-preview, unavailable_after) on * every surface (global grid, per-post, per-term, Quick Edit, * block editor, REST, WP-CLI) and conditional auto-noindex * rules driven by custom-field (ACF) matches. */ define( 'NOINDEX_SEO_VERSION', '3.6.0' ); /** * Option key holding the consolidated plugin settings array. * * @since 3.0.0 */ define( 'NOINDEX_SEO_SETTINGS_KEY', 'noindex_seo_settings' ); /** * Returns the boolean robots directives supported by the plugin. * * Boolean directives are simple flags: present in the robots output when on * (1), absent when off (0). * * @since 3.6.0 * * @return array Directive slugs. */ function noindex_seo_get_boolean_directives() { return array( 'noindex', 'nofollow', 'noarchive', 'nosnippet', 'noimageindex', 'notranslate' ); } /** * Returns the value-carrying robots directives supported by the plugin. * * Value directives render as `name:value` in the robots output. An empty * string ('') means the directive is off. * * @since 3.6.0 * * @return array Directive slugs. */ function noindex_seo_get_value_directives() { return array( 'max-snippet', 'max-image-preview', 'max-video-preview', 'unavailable_after' ); } /** * Returns every robots directive supported by the plugin (boolean + value). * * @since 3.6.0 * * @return array Directive slugs. */ function noindex_seo_get_directives() { return array_merge( noindex_seo_get_boolean_directives(), noindex_seo_get_value_directives() ); } /** * Normalizes a raw directive value to its canonical storage form. * * Boolean directives normalize to 0 or 1. Value directives normalize to '' * (off) or their canonical string value: * * - max-snippet / max-video-preview: integer >= -1 as a string (-1 = no limit). * - max-image-preview: 'none', 'standard' or 'large'. * - unavailable_after: 'Y-m-d H:i' in the site timezone (anything that does * not parse, including datetime-local 'T' separators are normalized or * rejected to ''). * * Every read path (settings merge, form handling, imports, post/term meta) * funnels through this function so the storage shape never drifts. * * @since 3.6.0 * * @param string $directive Directive slug. * @param mixed $raw Raw value from storage or user input. * @return int|string 0|1 for boolean directives, ''|string for value directives. */ function noindex_seo_normalize_directive_value( $directive, $raw ) { if ( in_array( $directive, noindex_seo_get_boolean_directives(), true ) ) { return ( is_scalar( $raw ) && 1 === absint( $raw ) ) ? 1 : 0; } if ( ! is_scalar( $raw ) ) { return ''; } $value = trim( (string) $raw ); if ( in_array( $directive, array( 'max-snippet', 'max-video-preview' ), true ) ) { if ( ! is_numeric( $value ) ) { return ''; } $int = (int) $value; return ( $int >= -1 ) ? (string) $int : ''; } if ( 'max-image-preview' === $directive ) { return in_array( $value, array( 'none', 'standard', 'large' ), true ) ? $value : ''; } if ( 'unavailable_after' === $directive ) { $value = str_replace( 'T', ' ', $value ); $dt = date_create_from_format( 'Y-m-d H:i', $value, wp_timezone() ); return false !== $dt ? $dt->format( 'Y-m-d H:i' ) : ''; } return ''; } /** * Formats a stored value directive for robots output. * * Value directives render as `name:value`; `unavailable_after` additionally * converts its stored 'Y-m-d H:i' site-time value to the RFC-style datetime * search engines expect (e.g. `unavailable_after: Wed, 25 Jun 2025 15:00:00 +0200`). * * @since 3.6.0 * * @param string $directive Directive slug. * @param string $value Normalized stored value (non-empty). * @return string Formatted directive token. */ function noindex_seo_format_value_directive( $directive, $value ) { if ( 'unavailable_after' === $directive ) { $dt = date_create_from_format( 'Y-m-d H:i', $value, wp_timezone() ); if ( false !== $dt ) { // RFC 1123-style with a numeric UTC offset ('O'): stable across // PHP versions, unlike the 'T' abbreviation. return $directive . ': ' . $dt->format( 'D, d M Y H:i:s O' ); } return ''; } return $directive . ':' . $value; } /** * Formats a directives map for flat-token output (meta tag, HTTP header). * * The map keys are directive names; values are `true` (boolean directive) or * the normalized stored value (value directive). Returns the `name` / * `name:value` tokens, e.g. `array( 'noindex', 'max-snippet:-1' )`. * * @since 3.6.0 * * @param array $directives Directive name => true or value. * @return array Formatted tokens. */ function noindex_seo_format_directives( array $directives ) { $tokens = array(); foreach ( $directives as $name => $value ) { if ( true === $value ) { $tokens[] = $name; } else { $token = noindex_seo_format_value_directive( $name, (string) $value ); if ( '' !== $token ) { $tokens[] = $token; } } } return $tokens; } /** * Returns the full consolidated settings array, merged with defaults. * * The shape is: * * [ * 'version' => 3, * 'contexts' => [ '' => [ '' => 0|1|'', ... ], ... ], * 'rules' => [ [ 'field' => '', 'value' => '' ], ... ], * 'config' => [ 'method' => 'meta', 'granular' => 0, ... ], * ] * * Boolean directives store 0|1 and value directives store '' (off) or their * canonical string value — see noindex_seo_normalize_directive_value(). * * The array is cached in a static variable per-request after the first read. * * @since 3.0.0 * @since 3.6.0 Value directives (max-snippet, max-image-preview, * max-video-preview, unavailable_after, notranslate) joined the * context grid, and the conditional auto-noindex rules were * added under the 'rules' key. * * @param bool $force_refresh Optional. Bypass the in-memory cache. Default false. * @return array{ * version: int, * contexts: array>, * rules: array, * config: array{ * method: string, * granular: int, * taxonomies_granular: int, * seoplugins: int, * delete_on_uninstall: int * } * } */ function noindex_seo_get_settings( $force_refresh = false ) { static $cached = null; if ( null !== $cached && ! $force_refresh ) { return $cached; } $defaults = array( 'version' => 3, 'contexts' => array(), 'rules' => array(), 'config' => array( 'method' => 'meta', 'granular' => 0, 'taxonomies_granular' => 0, 'seoplugins' => 0, 'delete_on_uninstall' => 0, ), ); // Seed every context × directive combination: 0 for boolean directives, // '' (off) for value directives. $directive_defaults = array(); foreach ( noindex_seo_get_boolean_directives() as $directive ) { $directive_defaults[ $directive ] = 0; } foreach ( noindex_seo_get_value_directives() as $directive ) { $directive_defaults[ $directive ] = ''; } foreach ( noindex_seo_get_contexts() as $context ) { $defaults['contexts'][ $context ] = $directive_defaults; } $saved = get_option( NOINDEX_SEO_SETTINGS_KEY, array() ); $saved = is_array( $saved ) ? $saved : array(); // Merge saved contexts without reordering defaults (so iteration is stable). if ( isset( $saved['contexts'] ) && is_array( $saved['contexts'] ) ) { foreach ( $defaults['contexts'] as $ctx => $ctx_directive_defaults ) { if ( isset( $saved['contexts'][ $ctx ] ) && is_array( $saved['contexts'][ $ctx ] ) ) { $saved_ctx = $saved['contexts'][ $ctx ]; foreach ( $ctx_directive_defaults as $dir => $default_value ) { $defaults['contexts'][ $ctx ][ $dir ] = array_key_exists( $dir, $saved_ctx ) ? noindex_seo_normalize_directive_value( $dir, $saved_ctx[ $dir ] ) : $default_value; } } } } // Conditional auto-noindex rules (3.6.0). if ( isset( $saved['rules'] ) ) { $defaults['rules'] = noindex_seo_sanitize_rules( $saved['rules'] ); } if ( isset( $saved['config'] ) && is_array( $saved['config'] ) ) { foreach ( $defaults['config'] as $key => $default_value ) { if ( ! isset( $saved['config'][ $key ] ) ) { continue; } $saved_config_value = $saved['config'][ $key ]; if ( is_int( $default_value ) ) { $defaults['config'][ $key ] = is_numeric( $saved_config_value ) ? (int) $saved_config_value : $default_value; } elseif ( is_string( $saved_config_value ) ) { $defaults['config'][ $key ] = $saved_config_value; } } } if ( isset( $saved['version'] ) && is_numeric( $saved['version'] ) ) { $defaults['version'] = (int) $saved['version']; } $cached = $defaults; return $cached; } /** * Reads a single directive value for a context from the consolidated settings. * * @since 3.0.0 * @since 3.6.0 Value directives return their normalized string value ('' = off) * instead of a boolean. * * @param string $context Context slug (e.g. 'single', 'attachment'). * @param string $directive Directive slug. * @return int|string 1 for an active boolean directive, 0 for an inactive one, * or the normalized value ('' = off) of a value directive. */ function noindex_seo_get_setting( $context, $directive ) { $settings = noindex_seo_get_settings(); if ( ! isset( $settings['contexts'][ $context ][ $directive ] ) ) { return in_array( $directive, noindex_seo_get_value_directives(), true ) ? '' : 0; } return $settings['contexts'][ $context ][ $directive ]; } /** * Sanitizes the conditional auto-noindex rules (TODO #11). * * Each rule is an exact-match pair: a post meta key (ACF fields and any * custom field store their values in post meta, so no ACF dependency is * needed) and the value that triggers noindex. Rules with an empty field or * value are dropped; at most 20 rules are kept; the plugin's own * `_noindex_seo_` meta keys are not valid rule fields (they are the output * of the plugin, not content data). * * @since 3.6.0 * * @param mixed $raw Untrusted rules array (from storage, form or import). * @return array Sanitized rules. */ function noindex_seo_sanitize_rules( $raw ) { if ( ! is_array( $raw ) ) { return array(); } $rules = array(); foreach ( $raw as $rule ) { if ( ! is_array( $rule ) || ! isset( $rule['field'], $rule['value'] ) ) { continue; } $field = is_scalar( $rule['field'] ) ? (string) preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $rule['field'] ) : ''; $value = is_scalar( $rule['value'] ) ? sanitize_text_field( (string) $rule['value'] ) : ''; if ( '' === $field || '' === $value || 0 === strpos( $field, '_noindex_seo_' ) ) { continue; } $rules[] = array( 'field' => $field, 'value' => $value, ); if ( count( $rules ) >= 20 ) { break; } } return $rules; } /** * Returns the first auto-noindex rule matching a post's meta, if any. * * A rule matches when the post's meta value for the rule field is exactly * equal (string comparison) to the rule value. The plugin's own * `_noindex_seo_` meta keys never match, even if a rule slipped through * sanitization. * * @since 3.6.0 * * @param int $post_id Post ID. * @return array{field: string, value: string}|null The matching rule, or null. */ function noindex_seo_matching_rule_for_post( $post_id ) { $post_id = absint( $post_id ); if ( ! $post_id ) { return null; } foreach ( noindex_seo_get_settings()['rules'] as $rule ) { if ( 0 === strpos( $rule['field'], '_noindex_seo_' ) ) { continue; } $meta = get_post_meta( $post_id, $rule['field'], true ); if ( is_scalar( $meta ) && (string) $meta === $rule['value'] ) { return $rule; } } return null; } /** * Collects the active directive map stored in a post's granular meta. * * Boolean directives that are on map to `true`; value directives map to their * normalized value (absent when off). * * @since 3.6.0 * * @param int $post_id Post ID. * @return array Directive name => true or value. */ function noindex_seo_get_post_directives_map( $post_id ) { $post_id = absint( $post_id ); $map = array(); if ( ! $post_id ) { return $map; } foreach ( noindex_seo_get_boolean_directives() as $directive ) { $meta_value = get_post_meta( $post_id, '_noindex_seo_' . $directive, true ); if ( is_scalar( $meta_value ) && 1 === absint( $meta_value ) ) { $map[ $directive ] = true; } } foreach ( noindex_seo_get_value_directives() as $directive ) { $meta_value = get_post_meta( $post_id, '_noindex_seo_' . $directive, true ); $value = is_scalar( $meta_value ) ? noindex_seo_normalize_directive_value( $directive, $meta_value ) : ''; if ( '' !== $value ) { $map[ $directive ] = $value; } } return $map; } /** * Collects the active directive map configured for a context. * * @since 3.6.0 * * @param string $context Context slug. * @return array Directive name => true or value. */ function noindex_seo_get_context_directives_map( $context ) { $map = array(); foreach ( noindex_seo_get_boolean_directives() as $directive ) { if ( 1 === noindex_seo_get_setting( $context, $directive ) ) { $map[ $directive ] = true; } } foreach ( noindex_seo_get_value_directives() as $directive ) { $value = noindex_seo_get_setting( $context, $directive ); if ( '' !== $value ) { $map[ $directive ] = $value; } } return $map; } /** * Reads a single value from the plugin's "config" sub-array. * * @since 3.0.0 * * @param string $key Config key (method|granular|seoplugins|delete_on_uninstall). * @param mixed $fallback Default if the key is missing. * @return mixed */ function noindex_seo_get_config( $key, $fallback = null ) { $settings = noindex_seo_get_settings(); if ( ! isset( $settings['config'][ $key ] ) ) { return $fallback; } return $settings['config'][ $key ]; } /** * Persists the full settings array and invalidates the runtime cache. * * @since 3.0.0 * * @param array $settings Settings array (same shape as noindex_seo_get_settings()). * @return void */ function noindex_seo_update_settings( array $settings ) { // Keep the version tag current. $settings['version'] = 3; update_option( NOINDEX_SEO_SETTINGS_KEY, $settings ); // Reset the static cache inside noindex_seo_get_settings() so the next read // picks up the new values without waiting for a new request. noindex_seo_get_settings( true ); } /** * Outputs robots directives using the configured implementation method. * * This function adds robots directives (noindex, nofollow, noarchive, nosnippet, noimageindex) * to instruct search engines how to handle the current page. It supports three implementation methods: * * - 'meta': HTML meta tags via wp_robots filter (default) * - 'header': HTTP X-Robots-Tag header * - 'both': Both HTML meta tags and HTTP headers * * The HTTP header method is more robust and works with non-HTML content (PDFs, images, feeds). * The meta tag method is more visible and easier for users to verify. * * @since 1.1.0 * @since 2.0.0 Added support for HTTP X-Robots-Tag headers and multiple implementation methods. * @since 2.0.0 Added support for multiple directives (noindex, nofollow, noarchive, nosnippet, noimageindex). * @since 3.1.3 Restored the fallback for WordPress < 5.7: directives are * printed as a classic tag on wp_head when * the wp_robots API is not available, so the plugin works from * WordPress 4.0 again. * @since 3.6.0 The $directives argument is now a map of directive name => * true (boolean directive) or the normalized string value * (value directive), so value-carrying directives such as * `max-snippet` render as `max-snippet:-1`. Flat lists of * boolean names passed by third-party code still work. * * @see https://developer.wordpress.org/reference/hooks/wp_robots/ * @see https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag * * @param string $method Implementation method: 'meta', 'header', or 'both'. Default 'meta'. * @param array $directives Directive map (name => true or value), or a flat * list of boolean names (pre-3.6.0 convention). * Default array('noindex' => true). * @return void */ function noindex_seo_metarobots( $method = 'meta', array $directives = array( 'noindex' => true ) ) { // Sanitize method. $valid_methods = array( 'meta', 'header', 'both' ); $method = in_array( $method, $valid_methods, true ) ? $method : 'meta'; // Normalize the directives map: accept a flat list of boolean names // (pre-3.6.0 calling convention) and drop unknown directives. $valid_directives = noindex_seo_get_directives(); $map = array(); foreach ( $directives as $name => $value ) { if ( is_int( $name ) && is_string( $value ) ) { // Flat list: sequential names. $name = $value; $value = true; } if ( ! in_array( $name, $valid_directives, true ) ) { continue; } if ( in_array( $name, noindex_seo_get_boolean_directives(), true ) ) { // absint( true ) === 1, so a single check covers both. if ( 1 === absint( $value ) ) { $map[ $name ] = true; } } else { $value = noindex_seo_normalize_directive_value( $name, $value ); if ( '' !== $value ) { $map[ $name ] = $value; } } } $directives = $map; if ( empty( $directives ) ) { return; // No valid directives to apply. } // Flat tokens (header value and classic meta tag). $tokens = noindex_seo_format_directives( $directives ); // Send HTTP header if requested. $header_sent = false; if ( in_array( $method, array( 'header', 'both' ), true ) ) { if ( ! headers_sent() ) { $header_value = implode( ', ', $tokens ); header( 'X-Robots-Tag: ' . $header_value, false ); $header_sent = true; } } // Add HTML meta tag if requested, or as fallback if headers already sent. $use_meta = in_array( $method, array( 'meta', 'both' ), true ); $fallback_needed = in_array( $method, array( 'header', 'both' ), true ) && ! $header_sent; if ( ! ( $use_meta || $fallback_needed ) ) { return; } if ( function_exists( 'wp_robots' ) ) { // WordPress 5.7+: inject the directives into the core robots API. // On WordPress older than 5.7 the wp_robots filter does not exist and the classic wp_head output below is used instead. add_filter( 'wp_robots', function ( array $robots ) use ( $directives ) { foreach ( $directives as $name => $value ) { $robots[ $name ] = ( true === $value ) ? true : $value; } return $robots; }, 99 // High priority to ensure our directives take precedence over other plugins. ); return; } // WordPress 4.0 - 5.6: classic tag on wp_head. add_action( 'wp_head', function () use ( $tokens ) { echo '' . "\n"; }, 1 // Early, so the tag sits near the top of the head like core output. ); } /** * Clear all robots directive meta values for a post. * * This helper function deletes all robots directive post meta fields for a given post ID. * Used when disabling granular control override or resetting directive settings. * * @since 2.0.0 * * @param int $post_id The post ID to clear directives for. * @return void */ function noindex_seo_clear_post_directives( $post_id ) { foreach ( noindex_seo_get_directives() as $directive ) { delete_post_meta( $post_id, '_noindex_seo_' . $directive ); } } /** * Determines whether to output robots directives based on page context and plugin settings. * * This function checks the current page context (e.g., single post, category archive, 404 page, etc.) * and evaluates plugin settings to determine which robots directives (noindex, nofollow, noarchive, * nosnippet, noimageindex) should be added. * * It retrieves settings efficiently using a transient cache. If the cache is not set, it pulls values * from the WordPress options API and rebuilds the cache. * * The list of contexts can be filtered via the {@see 'noindex_seo_contexts'} filter. * Once a matching context is found, it calls {@see noindex_seo_metarobots()} to apply the directives. * * @since 1.1.0 * @since 2.0.0 Added support for multiple directives (noindex, nofollow, noarchive, nosnippet, noimageindex). * * @global WP_Post $post The global post object, if available. * * @return void */ function noindex_seo_show() { /** * Filter the contexts and corresponding option keys used for robots directives. * * Custom option keys MUST follow the pattern `noindex_seo_{context}`. * Directive option keys for non-noindex directives are derived by replacing * the leading `noindex` with the directive name via str_replace(), e.g. * `noindex_seo_single` → `nofollow_seo_single`. Keys that do not start with * `noindex_seo_` are silently discarded. * * @since 1.0.0 * * @param array $contexts Associative array of context slug => option_key. */ $contexts = apply_filters( 'noindex_seo_contexts', array( 'single' => 'noindex_seo_single', 'woo_cart' => 'noindex_seo_woo_cart', 'woo_checkout' => 'noindex_seo_woo_checkout', 'woo_myaccount' => 'noindex_seo_woo_myaccount', 'page' => 'noindex_seo_page', 'privacy_policy' => 'noindex_seo_privacy_policy', 'attachment' => 'noindex_seo_attachment', 'category' => 'noindex_seo_category', 'tag' => 'noindex_seo_tag', 'author' => 'noindex_seo_author', 'post_type_archive' => 'noindex_seo_post_type_archive', 'date' => 'noindex_seo_date', 'day' => 'noindex_seo_day', 'month' => 'noindex_seo_month', 'year' => 'noindex_seo_year', 'archive' => 'noindex_seo_archive', 'search' => 'noindex_seo_search', 'error' => 'noindex_seo_error', 'front_page' => 'noindex_seo_front_page', 'home' => 'noindex_seo_home', 'singular' => 'noindex_seo_singular', 'paged' => 'noindex_seo_paged', 'preview' => 'noindex_seo_preview', 'customize_preview' => 'noindex_seo_customize_preview', 'time' => 'noindex_seo_time', ) ); // Validate filtered contexts to prevent injection of invalid option names. // phpstan-wordpress types apply_filters() based on its default argument (array). // The cast below ensures runtime safety if a filter callback returns a non-array. foreach ( (array) $contexts as $context => $option_key ) { // Ensure option_key follows expected pattern. // is_string() check is omitted: PHPStan guarantees $option_key is string // because apply_filters returns array based on its default argument. if ( 0 !== strpos( $option_key, 'noindex_seo_' ) ) { unset( $contexts[ $context ] ); } } // PRIORITY 1: Check for per-post/page override (granular control). // If granular control is enabled and we're on a singular post/page, // check if there's an override for this specific content. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( $granular_enabled && is_singular() ) { $post_id = get_queried_object_id(); if ( $post_id ) { $override = get_post_meta( $post_id, '_noindex_seo_override', true ); if ( $override ) { // Collect active directives (booleans and values) from post meta. $post_directives = noindex_seo_get_post_directives_map( $post_id ); // Apply post-specific directives if any are enabled. if ( ! empty( $post_directives ) ) { $opt = noindex_seo_get_config( 'method', 'meta' ); $implementation_method = is_string( $opt ) ? $opt : 'meta'; noindex_seo_metarobots( $implementation_method, $post_directives ); return; // Exit early - post meta takes precedence over global settings. } } } } // PRIORITY 1.5: Check for per-term override (granular control on taxonomies). // Runs after per-post (more specific) but before the global context settings. // Triggered on is_category() / is_tag() / is_tax() when 'taxonomies_granular' // is on AND the queried term has the override flag set in term meta. // Term meta requires WordPress 4.4+; on older versions this branch is skipped. if ( function_exists( 'get_term_meta' ) && noindex_seo_get_config( 'taxonomies_granular', 0 ) && ( is_category() || is_tag() || is_tax() ) ) { $term_id = get_queried_object_id(); if ( $term_id ) { $term_override = get_term_meta( $term_id, '_noindex_seo_override', true ); if ( $term_override ) { $term_directives = array(); foreach ( noindex_seo_get_boolean_directives() as $directive ) { $meta_value = get_term_meta( $term_id, '_noindex_seo_' . $directive, true ); if ( is_scalar( $meta_value ) && 1 === absint( $meta_value ) ) { $term_directives[ $directive ] = true; } } foreach ( noindex_seo_get_value_directives() as $directive ) { $meta_value = get_term_meta( $term_id, '_noindex_seo_' . $directive, true ); $value = is_scalar( $meta_value ) ? noindex_seo_normalize_directive_value( $directive, $meta_value ) : ''; if ( '' !== $value ) { $term_directives[ $directive ] = $value; } } if ( ! empty( $term_directives ) ) { $opt = noindex_seo_get_config( 'method', 'meta' ); $implementation_method = is_string( $opt ) ? $opt : 'meta'; noindex_seo_metarobots( $implementation_method, $term_directives ); return; } } } } // PRIORITY 1.55: Conditional auto-noindex rules (3.6.0). // A rule match applies noindex to the singular content being viewed — // more specific than the per-CPT and global context defaults, less // specific than an explicit per-post override (PRIORITY 1, which already // returned above when active). if ( is_singular() ) { $matched_rule = noindex_seo_matching_rule_for_post( get_queried_object_id() ); if ( null !== $matched_rule ) { $opt = noindex_seo_get_config( 'method', 'meta' ); $implementation_method = is_string( $opt ) ? $opt : 'meta'; noindex_seo_metarobots( $implementation_method, array( 'noindex' => true ) ); return; } } // PRIORITY 1.6: Per-CPT global defaults. // When the current request is a single from a public custom post type that // has at least one directive configured in its `cpt_{post_type}` context, // apply those directives and short-circuit before falling through to the // generic `single` global setting. Built-in post / page / attachment do // not have a `cpt_*` context (they have their own dedicated contexts), so // this branch is a no-op for them. if ( is_singular() ) { $post_type = get_post_type(); if ( $post_type && 'post' !== $post_type && 'page' !== $post_type && 'attachment' !== $post_type ) { $cpt_context = 'cpt_' . $post_type; $cpt_directives = noindex_seo_get_context_directives_map( $cpt_context ); if ( ! empty( $cpt_directives ) ) { $opt = noindex_seo_get_config( 'method', 'meta' ); $implementation_method = is_string( $opt ) ? $opt : 'meta'; noindex_seo_metarobots( $implementation_method, $cpt_directives ); return; } } } // PRIORITY 2: Apply global settings (existing behavior). // Try to get the options from the transient. $options = get_transient( 'noindex_seo_options' ); // Available directives (booleans and value-carrying, 3.6.0). $available_directives = noindex_seo_get_directives(); if ( false === $options || ! is_array( $options ) || empty( $options ) ) { // Transient not set; pull directive values from the consolidated settings. // The cache stores them keyed by the legacy `{directive}_seo_{context}` // option name so the rest of noindex_seo_show() does not need to know // about the storage layout change introduced in 3.0. $options = array(); foreach ( $contexts as $context => $option_key ) { foreach ( $available_directives as $directive ) { $directive_key = str_replace( 'noindex', $directive, (string) $option_key ); $options[ $directive_key ] = noindex_seo_get_setting( $context, $directive ); } } // Set the transient for 1 hour to cache the options. set_transient( 'noindex_seo_options', $options, HOUR_IN_SECONDS ); } // Define current conditions, ordered from most specific to most general. // Note on 'date' context: is_date() returns true for any date-based archive (day/month/year/time). // In normal WordPress, if is_date() is true, at least one specific date function should also be true. // However, this catch-all condition is kept for edge cases, custom implementations, or future // WordPress versions that might introduce new date archive types not covered by the specific functions. // While this condition may rarely (or never) be true in practice, it provides defensive coverage. // WooCommerce special pages (Cart, Checkout, My Account) are regular // pages; resolve them once so their dedicated contexts can run before // the generic 'page' context. $woo_context = is_page() ? noindex_seo_get_woo_context_for_page( get_queried_object_id() ) : ''; $current_conditions = array( 'single' => is_single(), 'woo_cart' => 'woo_cart' === $woo_context, 'woo_checkout' => 'woo_checkout' === $woo_context, 'woo_myaccount' => 'woo_myaccount' === $woo_context, 'page' => is_page(), 'attachment' => is_attachment(), 'privacy_policy' => function_exists( 'is_privacy_policy' ) && is_privacy_policy(), 'category' => is_category(), 'tag' => is_tag(), 'author' => is_author(), 'post_type_archive' => is_post_type_archive(), 'day' => is_day(), 'month' => is_month(), 'year' => is_year(), 'time' => is_time(), 'date' => is_date() && ! ( is_day() || is_month() || is_year() || is_time() ), // Catch-all for date archives. 'archive' => is_archive() && ! ( is_category() || is_tag() || is_author() || is_post_type_archive() || is_date() ), 'search' => is_search(), 'error' => is_404(), 'front_page' => is_front_page() && ! is_paged() && ! is_home(), 'home' => is_home() && ! is_paged(), 'singular' => is_singular() && ! ( is_single() || is_page() || is_attachment() ), 'paged' => is_paged() && ! is_front_page() && ! is_home(), 'preview' => is_preview(), 'customize_preview' => function_exists( 'is_customize_preview' ) && is_customize_preview(), ); // Get implementation method configuration. $opt = noindex_seo_get_config( 'method', 'meta' ); $implementation_method = is_string( $opt ) ? $opt : 'meta'; // Iterate through the contexts and collect active directives. foreach ( $contexts as $context => $option_key ) { if ( isset( $current_conditions[ $context ] ) && $current_conditions[ $context ] ) { // Collect all active directives for this context: booleans map to // true, value directives keep their cached string value. $active_directives = array(); foreach ( $available_directives as $directive ) { $directive_key = str_replace( 'noindex', $directive, (string) $option_key ); if ( ! isset( $options[ $directive_key ] ) || '' === $options[ $directive_key ] || 0 === $options[ $directive_key ] ) { continue; } $active_directives[ $directive ] = is_string( $options[ $directive_key ] ) ? $options[ $directive_key ] : true; } // Apply directives if any are active. if ( ! empty( $active_directives ) ) { noindex_seo_metarobots( $implementation_method, $active_directives ); break; // Prevent multiple meta tags from being added. } } } unset( $contexts, $options, $current_conditions, $available_directives ); } /** * Checks if configuration migration is needed and executes it. * * This function runs on plugin load and checks the configuration version stored in the database. * If the version is less than 2 (or doesn't exist), it migrates old single-directive options * to the new multi-directive system introduced in version 2.0. * * If the version is less than 3, it migrates the 110 individual `{directive}_seo_{context}` * options plus the five `noindex_seo_config_*` options into a single consolidated * `noindex_seo_settings` array (introduced in 3.0.0). * * Self-healing: even if the version claims migration is complete, the function * re-runs the v3 migration if the consolidated option is somehow missing. This * guards against partial failures (object cache staleness, request interruption * mid-migration, third-party plugins clearing options) that would otherwise leave * the site with no settings until manual intervention. * * @since 2.0.0 * @since 3.0.0 Added v2→v3 storage consolidation step and self-healing. * * @return void */ function noindex_seo_check_migration() { $current_config_version = get_option( 'noindex_seo_config_version', 0 ); // Check if we need to migrate to version 2. if ( $current_config_version < 2 ) { noindex_seo_migrate_to_v2(); } // Run the v3 migration if version < 3 OR if the consolidated option is // somehow missing despite the version claiming we already migrated. // Self-healing: this catches scenarios where a previous migration bumped // the version but did not persist the consolidated option (object cache // staleness, request interrupted mid-migration, third-party delete, etc.). $consolidated_exists = false !== get_option( NOINDEX_SEO_SETTINGS_KEY ); if ( $current_config_version < 3 || ! $consolidated_exists ) { noindex_seo_migrate_to_v3(); } } /** * Migrates configuration from version 1.x to version 2.0. * * Version 1.x had single options per context (e.g., noindex_seo_attachment). * Version 2.0 has 5 independent directives per context (e.g., noindex_seo_attachment, * nofollow_seo_attachment, noarchive_seo_attachment, etc.). * * This function: * 1. Reads existing noindex_seo_* options * 2. Preserves their values (they're already in the correct format) * 3. Initializes new directive options (nofollow, noarchive, nosnippet, noimageindex) to 0 * 4. Marks migration as complete by setting config version to 2 * 5. Clears the transient cache * * @since 2.0.0 * * @return void */ function noindex_seo_migrate_to_v2() { $contexts = noindex_seo_get_contexts(); $new_directives = array( 'nofollow', 'noarchive', 'nosnippet', 'noimageindex' ); // For each context, initialize new directives to 0. // The noindex directive already exists and will keep its value. foreach ( $contexts as $context ) { foreach ( $new_directives as $directive ) { $option_key = $directive . '_seo_' . $context; // Only set if it doesn't exist (shouldn't exist in v1.x). if ( false === get_option( $option_key ) ) { add_option( $option_key, 0 ); } } } // Mark migration as complete. update_option( 'noindex_seo_config_version', 2 ); // Clear transient cache. delete_transient( 'noindex_seo_options' ); } /** * Migrates configuration from version 2.x to version 3.0. * * Version 2.x stored settings across ~110 individual options: one option per * (directive, context) pair plus five `noindex_seo_config_*` options. Each of * those rows was autoloaded on every WordPress request. * * Version 3.0 consolidates them into a single autoloaded array option, * `noindex_seo_settings`, that the rest of the plugin reads through * `noindex_seo_get_settings()` / `noindex_seo_get_setting()` / * `noindex_seo_get_config()`. * * Migration is idempotent and safe to re-run: * * 1. Reads every legacy option (defaulting to 0 / 'meta' as appropriate). * 2. Builds the consolidated array. * 3. Writes the array via `update_option()` (autoloaded by default). * 4. Rewrites each legacy option with autoload=false so it stops counting * against the per-request autoload budget but remains readable for a * safe rollback to 2.x. These will be deleted in 4.0. * 5. Bumps `noindex_seo_config_version` to 3. * 6. Clears the transient cache. * * @since 3.0.0 * * @return void */ function noindex_seo_migrate_to_v3() { $contexts = noindex_seo_get_contexts(); $directives = array( 'noindex', 'nofollow', 'noarchive', 'nosnippet', 'noimageindex' ); $consolidated = array( 'version' => 3, 'contexts' => array(), 'config' => array( // Read directly from the legacy individual options — NOT via // noindex_seo_get_config(), which would read the consolidated option // we are in the middle of building. 'method' => get_option( 'noindex_seo_config_method', 'meta' ), 'granular' => get_option( 'noindex_seo_config_granular', 0 ), 'seoplugins' => get_option( 'noindex_seo_config_seoplugins', 0 ), 'delete_on_uninstall' => get_option( 'noindex_seo_config_delete_on_uninstall', 0 ), ), ); // Normalise config value types. $consolidated['config']['granular'] = $consolidated['config']['granular'] ? 1 : 0; $consolidated['config']['seoplugins'] = $consolidated['config']['seoplugins'] ? 1 : 0; $consolidated['config']['delete_on_uninstall'] = $consolidated['config']['delete_on_uninstall'] ? 1 : 0; if ( ! in_array( $consolidated['config']['method'], array( 'meta', 'header', 'both' ), true ) ) { $consolidated['config']['method'] = 'meta'; } foreach ( $contexts as $context ) { $consolidated['contexts'][ $context ] = array(); foreach ( $directives as $directive ) { $option_key = $directive . '_seo_' . $context; $value = get_option( $option_key, 0 ); $consolidated['contexts'][ $context ][ $directive ] = ( is_numeric( $value ) && 1 === (int) $value ) ? 1 : 0; } } // Write the consolidated option (autoloaded by default — single wp_options row). update_option( NOINDEX_SEO_SETTINGS_KEY, $consolidated ); // Mark each legacy option as non-autoloaded. update_option() short-circuits // when the value is unchanged (which is the case here — we are only flipping // the autoload flag), so we use a direct SQL UPDATE on the options table. // The options themselves remain readable for a safe rollback to 2.x; they // will be deleted entirely in 4.0. global $wpdb; // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching // Migration is a one-shot operation. Direct update is necessary because // update_option() does not change autoload when the value is unchanged. // This is a UPDATE (no result set), so caching is not applicable. foreach ( $contexts as $context ) { foreach ( $directives as $directive ) { $option_key = $directive . '_seo_' . $context; $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name = %s", $option_key ) ); } } foreach ( array( 'method', 'granular', 'seoplugins', 'delete_on_uninstall' ) as $config_key ) { $option_key = 'noindex_seo_config_' . $config_key; $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name = %s", $option_key ) ); } // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching // Mark migration complete and clear cache. update_option( 'noindex_seo_config_version', 3 ); delete_transient( 'noindex_seo_options' ); // Reset the in-memory settings cache so the rest of this request reads // from the new option instead of the just-stale state. noindex_seo_get_settings( true ); } add_action( 'template_redirect', 'noindex_seo_show' ); add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'noindex_seo_settings_link' ); add_action( 'admin_init', 'noindex_seo_register' ); add_action( 'admin_menu', 'noindex_seo_menu' ); add_action( 'admin_enqueue_scripts', 'noindex_seo_enqueue_admin_assets' ); add_action( 'plugins_loaded', 'noindex_seo_check_migration' ); add_action( 'init', 'noindex_seo_load_textdomain' ); /** * Loads the plugin's translated strings from the bundled languages directory. * * WordPress auto-loads translations from `wp-content/languages/plugins/`, but * the `.mo` files shipped in the plugin's own `languages/` directory require * this explicit call. Hooked on {@see 'init'} so the text domain is available * before any user-facing string is rendered. * * @since 3.1.2 * * @return void */ function noindex_seo_load_textdomain() { load_plugin_textdomain( 'noindex-seo', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' ); } /** * Excludes noindexed posts from the core XML sitemap (WP 5.5+). * * Two layers of exclusion: * 1. Whole-post-type exclusion: if the global setting for the context that * matches the post type has `noindex=1`, the entire post type is hidden * from the sitemap by setting `post__in = [0]` (an impossible ID, so * the query returns no rows). The relevant contexts are: * - 'singular' → applies to every public post type (catch-all). * - 'single' → applies to the built-in `post` post type. * - 'page' → applies to the built-in `page` post type. * - 'attachment'→ applies to the built-in `attachment` post type. * - 'cpt_{type}'→ applies to that custom post type (3.1.0+). * 1.5. WooCommerce special pages (cart / checkout / my account, 3.5.0+): * when their dedicated contexts have `noindex=1`, the specific page IDs * are dropped from the pages sitemap even if the 'page' context is not * noindexed. * 2. Per-post exclusion: if granular control is on, individual posts that * have `_noindex_seo_override=1` AND `_noindex_seo_noindex=1` in postmeta * are added to `post__not_in`. * * Hooked to the {@see 'wp_sitemaps_posts_query_args'} filter. * * @since 3.1.0 * * @param array $args WP_Query arguments for the sitemap post query. * @param string $post_type Post type being listed. * @return array Filtered arguments. */ function noindex_seo_filter_sitemap_posts( array $args, $post_type ) { // Layer 1: whole-post-type exclusion via global context settings. // 'singular' is the catch-all — if it is noindexed, hide everything. if ( 1 === noindex_seo_get_setting( 'singular', 'noindex' ) ) { $args['post__in'] = array( 0 ); return $args; } // Then check the specific context for the post type. $context_for_type = ''; if ( 'post' === $post_type ) { $context_for_type = 'single'; } elseif ( 'page' === $post_type ) { $context_for_type = 'page'; } elseif ( 'attachment' === $post_type ) { $context_for_type = 'attachment'; } else { $context_for_type = 'cpt_' . $post_type; } if ( 1 === noindex_seo_get_setting( $context_for_type, 'noindex' ) ) { $args['post__in'] = array( 0 ); return $args; } // Layer 1.5: WooCommerce special pages. They belong to the 'page' post // type but can carry their own dedicated contexts, so drop them from // the pages sitemap when those contexts are noindexed (WP 3.5.0+). if ( 'page' === $post_type ) { $woo_excluded = array(); foreach ( noindex_seo_get_woo_context_options() as $woo_context => $woo_option ) { if ( 1 !== noindex_seo_get_setting( $woo_context, 'noindex' ) ) { continue; } $woo_page_id = get_option( $woo_option, 0 ); if ( is_numeric( $woo_page_id ) && (int) $woo_page_id > 0 ) { $woo_excluded[] = (int) $woo_page_id; } } if ( ! empty( $woo_excluded ) ) { $existing = isset( $args['post__not_in'] ) && is_array( $args['post__not_in'] ) ? $args['post__not_in'] : array(); $args['post__not_in'] = array_merge( $existing, $woo_excluded ); } } // Layer 2: per-post exclusion via granular override or conditional rules. // Rule matches (3.6.0) always mean noindex, so they join the exclusion // query directly; the granular override only excludes when its noindex // directive is on. $meta_query = array( 'relation' => 'OR' ); if ( noindex_seo_get_config( 'granular', 0 ) ) { $meta_query[] = array( 'relation' => 'AND', array( 'key' => '_noindex_seo_override', 'value' => 1, ), array( 'key' => '_noindex_seo_noindex', 'value' => 1, ), ); } foreach ( noindex_seo_get_settings()['rules'] as $rule ) { $meta_query[] = array( 'key' => $rule['field'], 'value' => $rule['value'], ); } if ( count( $meta_query ) > 1 ) { $excluded = get_posts( array( 'post_type' => $post_type, 'fields' => 'ids', 'nopaging' => true, 'suppress_filters' => false, 'no_found_rows' => true, 'meta_query' => $meta_query, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query ) ); if ( ! empty( $excluded ) ) { $existing = isset( $args['post__not_in'] ) && is_array( $args['post__not_in'] ) ? $args['post__not_in'] : array(); $args['post__not_in'] = array_merge( $existing, $excluded ); } } return $args; } // The hook only exists on WP 5.5+; on older versions the filter simply never fires. add_filter( 'wp_sitemaps_posts_query_args', 'noindex_seo_filter_sitemap_posts', 10, 2 ); /** * Excludes noindexed terms from the core XML sitemap (WP 5.5+). * * Two layers, mirroring {@see noindex_seo_filter_sitemap_posts()}: * 1. Whole-taxonomy exclusion: if the global setting for the matching * context (`category`, `tag`, or any custom public taxonomy mapped to * its own context if present) has `noindex=1`, hide the entire taxonomy. * 2. Per-term exclusion: if per-term granular control is on, individual * terms with `_noindex_seo_override=1` AND `_noindex_seo_noindex=1` are * added to `exclude`. * * Hooked to the {@see 'wp_sitemaps_taxonomies_query_args'} filter. * * @since 3.1.0 * * @param array $args WP_Term_Query arguments for the sitemap term query. * @param string $taxonomy Taxonomy being listed. * @return array Filtered arguments. */ function noindex_seo_filter_sitemap_taxonomies( array $args, $taxonomy ) { // Layer 1: whole-taxonomy exclusion via global context settings. $context_for_tax = ''; if ( 'category' === $taxonomy ) { $context_for_tax = 'category'; } elseif ( 'post_tag' === $taxonomy ) { $context_for_tax = 'tag'; } if ( $context_for_tax && 1 === noindex_seo_get_setting( $context_for_tax, 'noindex' ) ) { // An empty `include` makes WP_Term_Query return zero rows. $args['include'] = array( 0 ); return $args; } // Layer 2: per-term exclusion via granular override. if ( noindex_seo_get_config( 'taxonomies_granular', 0 ) ) { $excluded = get_terms( array( 'taxonomy' => $taxonomy, 'fields' => 'ids', 'hide_empty' => false, 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query 'relation' => 'AND', array( 'key' => '_noindex_seo_override', 'value' => 1, ), array( 'key' => '_noindex_seo_noindex', 'value' => 1, ), ), ) ); if ( is_array( $excluded ) && ! empty( $excluded ) ) { $existing = isset( $args['exclude'] ) && is_array( $args['exclude'] ) ? $args['exclude'] : array(); $args['exclude'] = array_merge( $existing, $excluded ); } } return $args; } // The hook only exists on WP 5.5+; on older versions the filter simply never fires. add_filter( 'wp_sitemaps_taxonomies_query_args', 'noindex_seo_filter_sitemap_taxonomies', 10, 2 ); /** * Excludes user URLs from the core XML sitemap when author archives are * noindexed globally. * * The users sitemap exists to surface author archive URLs. If the global * `author` context has `noindex=1`, every author archive is non-indexable, * so the entire users sitemap should be empty. We hide every user by * setting `include = [0]` (an impossible ID). * * Hooked to the {@see 'wp_sitemaps_users_query_args'} filter. * * @since 3.1.0 * * @param array $args WP_User_Query arguments for the sitemap user query. * @return array Filtered arguments. */ function noindex_seo_filter_sitemap_users( array $args ) { if ( 1 === noindex_seo_get_setting( 'author', 'noindex' ) ) { $args['include'] = array( 0 ); } return $args; } // The hook only exists on WP 5.5+; on older versions the filter simply never fires. add_filter( 'wp_sitemaps_users_query_args', 'noindex_seo_filter_sitemap_users' ); /** * Registers the plugin's REST API routes. * * Two routes under the `noindex-seo/v1` namespace: * * - GET /wp-json/noindex-seo/v1/settings * Returns the consolidated settings array (contexts × directives + config). * Lets headless consumers read the global configuration. Read-only, public. * * - GET /wp-json/noindex-seo/v1/effective?post_id=123 * Returns the list of active directives for a specific post ID, computed * by the same precedence rules used on the front-end: per-post override → * per-CPT default → built-in `single` / `page` / `attachment` context. * Read-only, public (the directive result is the same info that would * appear in the HTML `` tag of a rendered page). * * Hooked to the {@see 'rest_api_init'} action. * * @since 3.1.0 * @since 3.1.3 No-ops on WordPress versions without the complete REST API * (pre-4.7): the routes are simply not registered there. * * @return void */ function noindex_seo_register_rest_routes() { // The complete REST API (including rest_authorization_required_code(), // used by both permission callbacks) exists since WordPress 4.7. if ( ! function_exists( 'register_rest_route' ) || ! function_exists( 'rest_authorization_required_code' ) ) { return; } register_rest_route( 'noindex-seo/v1', '/settings', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => 'noindex_seo_rest_get_settings', 'permission_callback' => 'noindex_seo_rest_settings_permission_check', ), ) ); register_rest_route( 'noindex-seo/v1', '/effective', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => 'noindex_seo_rest_get_effective', 'permission_callback' => 'noindex_seo_rest_effective_permission_check', 'args' => array( 'post_id' => array( 'type' => 'integer', 'required' => true, 'sanitize_callback' => 'absint', 'description' => __( 'Post ID to compute effective directives for.', 'noindex-seo' ), ), ), ), ) ); } // The rest_api_init action exists on all supported versions (floor: WP 4.7). add_action( 'rest_api_init', 'noindex_seo_register_rest_routes' ); /** * Permission callback for the /settings endpoint. * * The consolidated settings array reveals the site's full SEO strategy in a * single response (every context × directive combination plus internal * flags like delete_on_uninstall). That is admin-only information; an * unauthenticated caller could otherwise enumerate the entire noindex * configuration by hitting the endpoint once. Restrict to `manage_options`. * * @since 3.1.1 * * @return true|WP_Error True if the current user can manage options, WP_Error otherwise. */ function noindex_seo_rest_settings_permission_check() { if ( ! current_user_can( 'manage_options' ) ) { return new WP_Error( 'noindex_seo_rest_forbidden', __( 'You do not have permission to read the noindex SEO settings.', 'noindex-seo' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Permission callback for the /effective endpoint. * * The effective directives for a post are the same information that would * appear in the HTML `` tag (or `X-Robots-Tag` header) * when the post is rendered on the front-end. They are therefore public for * posts that are themselves publicly viewable: * * - `publish` status AND no password → public access (no auth required). * * For everything else (drafts, private posts, future/scheduled posts, * password-protected posts, trashed posts), the directives are admin-only * and the caller must have the `edit_post` capability for that post. * * If the requested post does not exist, permission is granted so that the * callback can return a proper 404 instead of a 401 (this matches the * behaviour of WP core's posts controller). * * @since 3.1.1 * * @param WP_REST_Request $request The current request, with `post_id`. * @return true|WP_Error True if access is allowed, WP_Error otherwise. */ function noindex_seo_rest_effective_permission_check( WP_REST_Request $request ) { $raw_post_id = $request->get_param( 'post_id' ); $post_id = is_numeric( $raw_post_id ) ? (int) $raw_post_id : 0; $post = get_post( $post_id ); // Missing post: defer to the callback, which returns a 404. if ( ! $post ) { return true; } // Public post (published + not password-protected): directives are // equivalent to what would appear in the rendered HTML. if ( 'publish' === $post->post_status && empty( $post->post_password ) ) { return true; } // Everything else requires edit permission for the specific post. if ( ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'noindex_seo_rest_forbidden', __( 'You do not have permission to read directives for this post.', 'noindex-seo' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * REST callback: returns the consolidated settings array. * * Strips the internal `version` key — that is an implementation detail that * callers should not depend on. Everything else (contexts, config) is exposed * verbatim so headless consumers can replicate the directive logic on their * own front-end. * * @since 3.1.0 * * @return WP_REST_Response The settings payload. */ function noindex_seo_rest_get_settings() { $settings = noindex_seo_get_settings(); unset( $settings['version'] ); return new WP_REST_Response( $settings, 200 ); } /** * REST callback: computes the active directives for a specific post ID. * * Mirrors the precedence used by {@see noindex_seo_show()} for the singular * branch: * * 1. Per-post override (postmeta `_noindex_seo_override=1` + the five * directive meta keys). * 2. Per-CPT default (`cpt_{post_type}` context in consolidated settings). * 3. Built-in context for the post type (`single` for posts, `page` for * pages, `attachment` for attachments). * * Returns the directive list and the implementation method so the consumer * knows whether to render an HTML meta tag, send an X-Robots-Tag header, or * both. * * @since 3.1.0 * @since 3.5.0 WooCommerce special pages resolve their dedicated context * first and fall back to the generic 'page' context when it * carries no active directives — the same precedence as the * front-end. * @since 3.6.0 Value-carrying directives return as `name:value` tokens * (e.g. `max-snippet:-1`), and matching conditional rules * surface as source `auto_rule`. * * @param WP_REST_Request $request Request with `post_id` param. * @return WP_REST_Response The effective-directives payload. */ function noindex_seo_rest_get_effective( WP_REST_Request $request ) { $raw_post_id = $request->get_param( 'post_id' ); $post_id = is_numeric( $raw_post_id ) ? (int) $raw_post_id : 0; $post = get_post( $post_id ); if ( ! $post ) { return new WP_REST_Response( array( 'code' => 'noindex_seo_post_not_found', 'message' => __( 'No post exists with that post_id.', 'noindex-seo' ), 'data' => array( 'status' => 404 ), ), 404 ); } $source = 'global_setting'; $directive_map = array(); // Step 1: per-post override (booleans + values from post meta). $override_raw = get_post_meta( $post_id, '_noindex_seo_override', true ); $override = ( is_scalar( $override_raw ) && 1 === absint( $override_raw ) ) ? 1 : 0; if ( $override ) { $directive_map = noindex_seo_get_post_directives_map( $post_id ); if ( ! empty( $directive_map ) ) { $source = 'post_meta'; } } // Step 1.5: conditional auto-noindex rules (3.6.0) — same precedence as // the front-end (below an explicit override, above context defaults). if ( 'global_setting' === $source && null !== noindex_seo_matching_rule_for_post( $post_id ) ) { $directive_map = array( 'noindex' => true ); $source = 'auto_rule'; } // Step 2 + 3: fall back to per-CPT or built-in context. if ( 'global_setting' === $source ) { $post_type = $post->post_type; if ( 'page' === $post_type ) { // WooCommerce special pages (cart, checkout, my account) have // their own contexts; mirror the front-end precedence. $context = noindex_seo_get_woo_context_for_page( $post->ID ); if ( '' === $context ) { $context = 'page'; } } elseif ( 'post' === $post_type ) { $context = 'single'; // The storage context for built-in posts is 'single'. } elseif ( 'attachment' === $post_type ) { $context = 'attachment'; } else { $context = 'cpt_' . $post_type; } $directive_map = noindex_seo_get_context_directives_map( $context ); // Mirror noindex_seo_show(): a WooCommerce special page whose dedicated // context carries no active directives falls back to the generic // 'page' context (the same iteration order the front-end uses). if ( empty( $directive_map ) && 'page' === $post_type && 0 === strpos( $context, 'woo_' ) ) { $directive_map = noindex_seo_get_context_directives_map( 'page' ); } } $method_raw = noindex_seo_get_config( 'method', 'meta' ); $method = is_string( $method_raw ) ? $method_raw : 'meta'; return new WP_REST_Response( array( 'post_id' => $post_id, 'post_type' => $post->post_type, 'directives' => noindex_seo_format_directives( $directive_map ), 'method' => $method, 'source' => $source, ), 200 ); } /** * Invalidates the hourly transient cache whenever the consolidated settings * option is written — no matter who wrote it (admin form, WP-CLI, REST, or * a third-party plugin calling update_option / add_option directly). * * The transient caches the rendered directive map for `noindex_seo_show()`. * Without these hooks, programmatic edits would stay stale for up to one hour. * * Two hooks are needed because WordPress dispatches writes differently: * - `update_option_{key}` fires only when an existing option is updated. * - `add_option_{key}` fires when a new option row is created. WordPress * routes `update_option()` through `add_option()` internally when the * option does not yet exist, so without this second hook the first write * after install would not clear the transient. * * Hooked to both the {@see 'update_option_noindex_seo_settings'} and * {@see 'add_option_noindex_seo_settings'} actions. * * @since 3.0.0 * * @return void */ function noindex_seo_invalidate_cache_on_settings_update() { delete_transient( 'noindex_seo_options' ); } add_action( 'update_option_' . NOINDEX_SEO_SETTINGS_KEY, 'noindex_seo_invalidate_cache_on_settings_update' ); add_action( 'add_option_' . NOINDEX_SEO_SETTINGS_KEY, 'noindex_seo_invalidate_cache_on_settings_update' ); /** * Returns the plugin's directive icons as SVG markup, keyed by directive. * * The icons follow the WordPress admin icon style (24x24 viewBox, 2px * currentColor strokes): the directive's concept in the upper-left corner * plus a "no" minus badge in the lower-right corner. * * Registered with the WordPress Icons API (WP 7.1+) by * {@see noindex_seo_register_icons()}; on older versions the emoji fallback * of {@see noindex_seo_get_directive_icon_html()} is used instead. * * @since 3.5.0 * * @return array Directive slug => SVG markup. */ function noindex_seo_get_directive_svg_icons() { $badge = ''; $open = ''; return array( 'noindex' => $open . '' . $badge . $close, 'nofollow' => $open . '' . $badge . $close, 'noarchive' => $open . '' . $badge . $close, 'nosnippet' => $open . '' . $badge . $close, 'noimageindex' => $open . '' . $badge . $close, 'notranslate' => $open . '' . $badge . $close, ); } /** * Registers the plugin's directive icons with the WordPress Icons API. * * WordPress 7.2 renders its own admin chrome through the icon registry * ({@see wp_register_icon()} / {@see wp_get_icon()}, introduced in 7.1) — * core replaced the admin bar and menu dashicons with SVG. Registering our * directive icons there lets the plugin use the same crisp, color-adaptive * rendering on WP 7.2+ while the emoji fallback keeps WordPress 7.0 and 7.1 * fully working. * * The SVG path is gated to WP 7.2+ on purpose: 7.1's icon sanitizer does not * allow `rect`/`circle` or the `stroke*` attributes (the stroke-based icons * would be stripped to unstyled fragments), and 7.1 rejects the `public` * collection property with a doing-it-wrong notice on every request. * * The collection is private (not exposed via REST or the editor icon picker): * the icons are only consumed by this plugin's admin UI. * * Hooked to the {@see 'init'} action; every consumer of the icons renders * later than init. * * @since 3.5.0 * * @return void */ function noindex_seo_register_icons() { // The Icons API exists since WordPress 7.1; without it (WP 7.0) this is // a no-op and noindex_seo_get_directive_icon_html() returns the emoji // fallback. if ( ! function_exists( 'wp_register_icon_collection' ) || ! function_exists( 'wp_register_icon' ) ) { return; } // WP 7.2 extended the icon sanitizer (rect/circle, stroke attributes) and // added the 'public' collection property; '7.2-alpha1' (not '7.2') so beta // and RC builds of 7.2 qualify for the SVG path. if ( version_compare( (string) get_bloginfo( 'version' ), '7.2-alpha1', '<' ) ) { return; } // Guarded above: the API exists since WP 7.1 while the plugin floor is 7.0. wp_register_icon_collection( 'noindex-seo', array( 'label' => 'noindex SEO', 'description' => 'Robots directive icons for the noindex SEO admin UI.', 'public' => false, ) ); foreach ( noindex_seo_get_directive_svg_icons() as $directive => $svg ) { // Guarded above: the API exists since WP 7.1 while the plugin floor is 7.0. wp_register_icon( 'noindex-seo/' . $directive, array( 'label' => 'noindex SEO: ' . $directive, 'content' => $svg, ) ); } } add_action( 'init', 'noindex_seo_register_icons' ); /** * Returns the rendered icon markup for a robots directive. * * Dual-path rendering for backwards compatibility: * * - WordPress 7.2+: the SVG icon registered by {@see noindex_seo_register_icons()} * through the core Icons API ({@see wp_get_icon()}) — 16px, aria-hidden, * color-adaptive via currentColor. Rendering is consistent on every OS, * unlike emoji. * - WordPress 7.0 - 7.1 (and any state where the icon is not registered): * the legacy emoji glyph, escaped and hidden from assistive technology. * * @since 3.5.0 * * @param string $directive Directive slug (noindex|nofollow|noarchive|nosnippet|noimageindex). * @return string Safe-to-embed icon markup (SVG from the plugin's own registry, or the escaped emoji fallback). */ function noindex_seo_get_directive_icon_html( $directive ) { if ( function_exists( 'wp_get_icon' ) ) { // Guarded: the API exists since WP 7.1 while the plugin floor is 7.0. $svg = wp_get_icon( 'noindex-seo/' . $directive, array( 'size' => 16, 'class' => 'noindex-seo-directive-icon', ) ); if ( '' !== $svg ) { return $svg; } } $emoji = array( 'noindex' => '🔍', 'nofollow' => '🔗', 'noarchive' => '💾', 'nosnippet' => '📄', 'noimageindex' => '🖼️', ); // The emoji is decorative (the directive name is always rendered next to // it), so hide it from assistive technology like the SVG path does. return isset( $emoji[ $directive ] ) ? '' : ''; } /** * Enqueues admin CSS and JavaScript assets. * * The stylesheet loads on every admin screen where the plugin renders UI: * the settings page, the post list (Robots column + Quick Edit + bulk * actions), the post editor (meta box), and the term editor (per-term * panel) — gated by the same configuration flags that gate the UI itself. * The interactive JavaScript only loads on the settings page. * * @since 2.0.0 * @since 3.1.6 Stylesheet also loads on list/edit/term screens so the * meta box, Quick Edit, columns and term panel are styled * through classes instead of inline styles (audit M7). * Gate widened to the `edit-tags` term-list screens and the * `attachment` Edit-Media screen (deploy-audit W1). * * @param string $hook The current admin page hook. * @return void */ function noindex_seo_enqueue_admin_assets( $hook ) { $is_settings_page = ( 'settings_page_noindex_seo' === $hook ); $load_style = $is_settings_page; if ( ! $load_style ) { $screen = get_current_screen(); if ( $screen ) { if ( noindex_seo_get_config( 'granular', 0 ) && in_array( $screen->base, array( 'edit', 'post', 'attachment' ), true ) ) { $load_style = true; } elseif ( noindex_seo_get_config( 'taxonomies_granular', 0 ) && in_array( $screen->base, array( 'term', 'edit-tags' ), true ) ) { $load_style = true; } } } if ( ! $load_style ) { return; } // Enqueue admin CSS.. wp_enqueue_style( 'noindex-seo-admin', plugins_url( 'assets/css/admin.css', __FILE__ ), array(), NOINDEX_SEO_VERSION, 'all' ); // The interactive script is only needed on the settings page.. if ( ! $is_settings_page ) { return; } // Enqueue admin JavaScript.. wp_enqueue_script( 'noindex-seo-admin', plugins_url( 'assets/js/admin.js', __FILE__ ), array( 'jquery' ), NOINDEX_SEO_VERSION, true ); // Localize script with translations.. wp_localize_script( 'noindex-seo-admin', 'noindexSeoAdmin', array( 'successMessage' => __( 'Settings saved successfully!', 'noindex-seo' ), 'expandAll' => __( 'Expand All', 'noindex-seo' ), 'collapseAll' => __( 'Collapse All', 'noindex-seo' ), ) ); } /** * Enqueue Gutenberg sidebar panel assets. * * Loads the JavaScript for the native Gutenberg sidebar panel * that allows editing robots directives in the Block Editor. * * @since 2.0.0 * * @return void */ function noindex_seo_enqueue_editor_assets() { // Check if granular control is enabled. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( ! $granular_enabled ) { return; } // Get the current screen. $screen = get_current_screen(); // Only load in block editor for supported post types. // WP_Screen::is_block_editor() exists since WordPress 5.0; older versions // never use the block editor, so the script is not loaded there. if ( ! $screen || version_compare( get_bloginfo( 'version' ), '5.0', '<' ) ) { return; } // is_block_editor() exists since WP 5.0; this callback only runs on WP 5.0+ because the hook only fires there. if ( ! $screen->is_block_editor() ) { return; } // Enqueue editor sidebar script. wp_enqueue_script( 'noindex-seo-editor-sidebar', plugins_url( 'assets/js/editor-sidebar.js', __FILE__ ), array( 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data', 'wp-i18n', ), NOINDEX_SEO_VERSION, true ); // Set up translations for the script (wp_set_script_translations exists // since WordPress 5.0; on older versions the block editor is never used). if ( function_exists( 'wp_set_script_translations' ) ) { wp_set_script_translations( 'noindex-seo-editor-sidebar', 'noindex-seo' ); } } // The action only exists on WP 5.0+; on older versions it simply never fires. add_action( 'enqueue_block_editor_assets', 'noindex_seo_enqueue_editor_assets' ); /** * Adds a "Settings" link to the plugin row actions on the Plugins admin screen. * * This function appends a direct link to the plugin's settings page within the list of action links * shown for the plugin on the Plugins page (`/wp-admin/plugins.php`). This improves user accessibility * by allowing quick access to the plugin's configuration page. * * Hooked to the {@see 'plugin_action_links_{plugin_basename}'} filter. * * @since 1.0.0 * * @param array $links Array of existing action links for the plugin. * @return array Modified array including the "Settings" link. */ function noindex_seo_settings_link( array $links ) { $settings_link = '' . esc_html__( 'Settings', 'noindex-seo' ) . ''; $links[] = $settings_link; return $links; } /** * Returns the WooCommerce context slugs mapped to the wp_options that hold * each special page's ID. * * WooCommerce stores the Cart, Checkout and My Account page IDs in plain * options, so detection needs no WooCommerce code — the plugin works from * the option values alone. Without WooCommerce the options do not exist * and every lookup returns an empty context. * * @since 3.5.0 * * @return array context slug => option name. */ function noindex_seo_get_woo_context_options() { return array( 'woo_cart' => 'woocommerce_cart_page_id', 'woo_checkout' => 'woocommerce_checkout_page_id', 'woo_myaccount' => 'woocommerce_myaccount_page_id', ); } /** * Returns the WooCommerce context matching a page ID, if any. * * My Account endpoints (e.g. /my-account/orders/) and the checkout * order-pay / order-received endpoints share their parent page's ID, so * they are covered by the same lookup. * * @since 3.5.0 * * @param int|string $page_id Page ID to look up. * @return string Context slug ('woo_cart', 'woo_checkout', 'woo_myaccount') or ''. */ function noindex_seo_get_woo_context_for_page( $page_id ) { // No static cache: get_option() is served from the options cache, and a // cached map would go stale when the page options change mid-request // (or between tests). foreach ( noindex_seo_get_woo_context_options() as $context => $option_name ) { $page_option = get_option( $option_name, 0 ); if ( is_numeric( $page_option ) && (int) $page_option === (int) $page_id && (int) $page_id > 0 ) { return $context; } } return ''; } /** * Registers the "noindex SEO" settings page in the WordPress admin menu. * * This function adds an entry under the "Settings" menu in the WordPress admin area, * which links to the plugin's main configuration page. The settings page is only accessible * to users with the 'manage_options' capability. * * Internally uses {@see add_options_page()} to register the page. * * @since 1.0.0 * * @return void */ function noindex_seo_menu() { add_options_page( __( 'noindex SEO', 'noindex-seo' ), __( 'noindex SEO', 'noindex-seo' ), 'manage_options', 'noindex_seo', 'noindex_seo_admin' ); } /** * Returns the canonical list of page contexts recognised by the plugin. * * Single source of truth for the contexts that the plugin registers options for, * migrates, processes from form submissions, and cleans up on uninstall. * * The list is intentionally a flat indexed array of slugs; the per-context page * detection map lives separately in {@see noindex_seo_show()} (where it can be * filtered via the `noindex_seo_contexts` filter). * * As of 3.1.0 the list also includes one `cpt_{post_type}` slug per public * custom post type (i.e. public + non-built-in), so the plugin can apply * per-CPT global defaults instead of every CPT falling into the generic * 'single' bucket. * * Note: `uninstall.php` cannot call this function (the main plugin file is not * loaded during uninstall), so it keeps its own copy in sync. * * @since 2.0.2 * @since 3.1.0 Appended per-CPT contexts (cpt_{post_type}) for public custom post types. * * @return array List of context slugs. */ function noindex_seo_get_contexts() { $base = array( 'archive', 'attachment', 'author', 'category', 'customize_preview', 'date', 'day', 'front_page', 'home', 'month', 'page', 'paged', 'post_type_archive', 'preview', 'privacy_policy', 'search', 'single', 'singular', 'tag', 'time', 'woo_cart', 'woo_checkout', 'woo_myaccount', 'year', 'error', ); // Append one context per public custom post type (excluding the built-in // post / page / attachment which already have their own contexts). // CPTs are registered on init; calling this before init returns no CPTs, // which is fine — the contexts list is only consulted at runtime / in admin. $cpts = get_post_types( array( 'public' => true, '_builtin' => false, ), 'names' ); foreach ( $cpts as $cpt_name ) { $base[] = 'cpt_' . $cpt_name; } return $base; } /** * Returns a safe display label for a custom post type object. * * Helper for the settings page: prefers the plural labels->name and falls * back to the raw post type slug when the labels object is incomplete. * * @since 3.1.3 * * @param object $cpt A WP_Post_Type object (or anything exposing ->name). * @return string The label to display. */ function noindex_seo_get_cpt_label( $cpt ) { if ( isset( $cpt->labels->name ) && '' !== (string) $cpt->labels->name ) { return (string) $cpt->labels->name; } if ( isset( $cpt->name ) ) { return (string) $cpt->name; } return ''; } /** * Registers all settings used by the 'noindex SEO' plugin. * * This function registers individual options for each context and directive combination. * Each context (e.g., single posts, category pages, archives, etc.) can have multiple * directives (noindex, nofollow, noarchive, nosnippet, noimageindex) applied independently. * * Each setting is stored as an integer (0 or 1), where 1 indicates that the directive is enabled * for that context. * * All settings are grouped under the option group 'noindexseo' and will be handled by the * WordPress Settings API when the options form is submitted. * * Also registers the general configuration options. * The transient cache is cleared inside noindex_seo_process_form() after every successful form save. * * @since 1.0.0 * @since 2.0.0 Added support for multiple directives per context. * @since 2.0.2 Removed dead `update_option_noindexseo` reference (the hook never fired). * @since 3.1.3 Uses the two-argument register_setting() form: the third * $args array is only supported since WordPress 4.7, and all * sanitization already happens in the admin-post form handler. * * @return void */ function noindex_seo_register() { $contexts = noindex_seo_get_contexts(); $directives = noindex_seo_get_directives(); // Register each directive for each context. foreach ( $contexts as $context ) { foreach ( $directives as $directive ) { register_setting( 'noindexseo', $directive . '_seo_' . $context ); } } register_setting( 'noindexseo', 'noindex_seo_config_seoplugins' ); register_setting( 'noindexseo', 'noindex_seo_config_method' ); register_setting( 'noindexseo', 'noindex_seo_config_granular' ); register_setting( 'noindexseo', 'noindex_seo_config_delete_on_uninstall' ); // NOTE: 'noindexseo' is the Settings API *group* name, not an option name. // update_option_noindexseo would never fire; the transient is cleared explicitly // inside noindex_seo_process_form() after every successful form save. } /** * Deprecated: clears the cached plugin settings stored in the transient. * * Was previously hooked to `update_option_noindexseo`, a hook that never fires * because `noindexseo` is the Settings API group name, not an option name. The * transient is now cleared directly inside {@see noindex_seo_process_form()} * after every successful form save. * * Kept as a deprecation shim for one release cycle in case third-party code * called the function directly. * * @since 1.0.0 * @since 2.0.2 Deprecated; no longer hooked by the plugin. Callers should * delete the `noindex_seo_options` transient directly via * `delete_transient( 'noindex_seo_options' )`. * * @return void */ function noindex_seo_clear_transient() { _deprecated_function( __FUNCTION__, '2.0.2', 'delete_transient( \'noindex_seo_options\' )' ); delete_transient( 'noindex_seo_options' ); } /** * Detects potential conflicts with other SEO plugins and displays an admin notice. * * This function checks for the presence of known SEO plugins that may conflict with * the functionality of 'noindex SEO'. If a conflicting plugin is active and the user * has not opted to suppress warnings (via the 'noindex_seo_config_seoplugins' option), * a dismissible admin notice is displayed to alert the site administrator. * * The list of conflicting plugins includes popular SEO tools such as Yoast SEO, Rank Math, * SEOPress, and others. The check is performed using {@see is_plugin_active()}. * * Hooked to the {@see 'admin_init'} action. * * @since 1.1.0 * * @return void */ function noindex_seo_detect_conflicts() { $option_config_seoplugins = noindex_seo_get_config( 'seoplugins', 0 ); if ( ! ( is_scalar( $option_config_seoplugins ) ? absint( $option_config_seoplugins ) : 0 ) ) { // Include the plugin.php file if the function is not available.. if ( ! function_exists( 'is_plugin_active' ) ) { include_once ABSPATH . 'wp-admin/includes/plugin.php'; } // Define an associative array of conflicting plugins: slug/file => real plugin name. // Filterable since 3.0.0 so third-party code can extend or replace the list // (e.g. to add The SEO Framework Pro, Slim SEO Pack vs Slim SEO, etc.). $conflicting_plugins = apply_filters( 'noindex_seo_conflicting_plugins', array( 'all-in-one-seo-pack/all_in_one_seo_pack.php' => 'All in One SEO', 'premium-seo-pack/index.php' => 'Premium SEO Pack', 'seo-by-rank-math/rank-math.php' => 'Rank Math SEO', 'wp-seopress/seopress.php' => 'SEOPress', 'slim-seo/slim-seo.php' => 'Slim SEO', 'squirrly-seo/squirrly.php' => 'Squirrly SEO', 'autodescription/autodescription.php' => 'The SEO Framework', 'wordpress-seo/wp-seo.php' => 'Yoast SEO', ) ); // Iterate through the conflicting plugins to check if any are active. $found_conflict = false; foreach ( $conflicting_plugins as $plugin_path => $plugin_name ) { if ( is_plugin_active( $plugin_path ) ) { // Add an admin notice if a conflicting plugin is active.. add_action( 'admin_notices', function () use ( $plugin_name ) { echo '

'; // translators: plugin name. printf( esc_html__( 'noindex SEO has detected that %s is active. This may cause conflicts. Please configure the options accordingly.', 'noindex-seo' ), esc_html( $plugin_name ) ); echo '

'; } ); $found_conflict = true; break; // Stop checking after finding the first conflict. } } // Runtime verification (3.2.0): when no known plugin conflicts, check // whether anything else is actually emitting robots directives through // the wp_robots API — this also catches themes and unknown plugins. // Only possible on WordPress 5.7+ (the filter does not exist earlier). if ( ! $found_conflict && function_exists( 'has_filter' ) && has_filter( 'wp_robots' ) ) { $foreign_callbacks = noindex_seo_get_foreign_robots_callbacks(); if ( ! empty( $foreign_callbacks ) ) { add_action( 'admin_notices', function () use ( $foreign_callbacks ) { echo '

'; // translators: %s: comma-separated list of wp_robots callbacks. printf( esc_html__( 'noindex SEO has detected that another plugin or theme is adding robots directives through the wp_robots API (%s). This may cause conflicts. Please configure the options accordingly.', 'noindex-seo' ), esc_html( implode( ', ', $foreign_callbacks ) ) ); echo '

'; } ); } } } } add_action( 'admin_init', 'noindex_seo_detect_conflicts' ); /** * Returns the wp_robots filter callbacks that do not belong to WordPress * core or to this plugin. * * Runtime conflict verification for {@see noindex_seo_detect_conflicts()}: * instead of trusting plugin slugs, this inspects the callbacks actually * registered on the `wp_robots` filter. Core registers plain functions * (wp_robots_noindex, wp_robots_noindex_embeds, wp_robots_noindex_search, * wp_robots_max_image_preview_large and, conditionally, wp_robots_no_robots); * anything else — named functions from other code, class methods, or * closures — is a third-party robots emitter. * * Only meaningful on WordPress 5.7+; on older versions the filter does not * exist and an empty array is returned. * * @since 3.2.0 * * @return string[] Unique readable callback identifiers ('function', * 'Class::method' or 'Closure'). */ function noindex_seo_get_foreign_robots_callbacks() { $foreign = array(); $wp_filter = isset( $GLOBALS['wp_filter'] ) && is_array( $GLOBALS['wp_filter'] ) ? $GLOBALS['wp_filter'] : array(); $robots_hook = isset( $wp_filter['wp_robots'] ) ? $wp_filter['wp_robots'] : null; if ( ! $robots_hook instanceof WP_Hook ) { return $foreign; } /** * Filter the wp_robots callbacks considered native to WordPress core. * * Third-party code can extend this list if it needs to mark its own * callback as expected (e.g. a site-specific mu-plugin). * * @since 3.2.0 * * @param string[] $core_callbacks Function names registered by core on wp_robots. */ $core_callbacks = apply_filters( 'noindex_seo_core_robots_callbacks', array( 'wp_robots_noindex', 'wp_robots_noindex_embeds', 'wp_robots_noindex_search', 'wp_robots_max_image_preview_large', 'wp_robots_no_robots', ) ); foreach ( $robots_hook->callbacks as $callbacks ) { foreach ( $callbacks as $callback ) { $function = $callback['function']; if ( $function instanceof Closure ) { $identifier = 'Closure'; } elseif ( is_string( $function ) ) { if ( in_array( $function, $core_callbacks, true ) || 0 === strpos( $function, 'noindex_seo_' ) ) { continue; } $identifier = $function; } elseif ( is_array( $function ) ) { $class = is_object( $function[0] ) ? get_class( $function[0] ) : (string) $function[0]; if ( 0 === strpos( $class, 'noindex_seo_' ) || 0 === strpos( $class, 'Noindex_Seo_' ) ) { continue; } $identifier = $class . '::' . (string) $function[1]; } else { continue; } if ( ! in_array( $identifier, $foreign, true ) ) { $foreign[] = $identifier; } } } return $foreign; } /** * Processes the form submission for the 'noindex SEO' plugin settings. * * This function handles the saving of plugin options submitted from the custom admin form. * It first verifies the current user's capability and nonce for security. Then it resets all * registered options to `0`, and selectively updates those submitted as checked in the form. * * The settings page is tabbed (General / SEO Settings), and only the active * tab's fields are present in the POST body. The form carries a * `noindex_seo_form_scope` marker so the handler knows which group to * process and preserves the values of the other group untouched. * * Hooked to the {@see 'admin_post_update_noindex_seo'} action. * * @since 1.2.0 * @since 2.0.0 Added support for multiple directives (noindex, nofollow, noarchive, nosnippet, noimageindex). * @since 3.1.5 Nonce verification split out of the capability check: * check_admin_referer() dies on failure instead of returning * false, so `! check_admin_referer()` was dead code. * @since 3.3.0 Tab-scoped processing: 'settings' saves only the directive * grid, 'general' only the configuration options; the other * group is preserved. The redirect returns to the saved tab. * * @return void */ function noindex_seo_process_form() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Permission denied.', 'noindex-seo' ) ); } check_admin_referer( 'update_noindex_seo_nonce' ); // Which tab the form was submitted from. Unknown or missing scope // defaults to the directive grid (the plugin's main surface). // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified above. $scope = ( isset( $_POST['noindex_seo_form_scope'] ) && is_string( $_POST['noindex_seo_form_scope'] ) ) ? sanitize_key( wp_unslash( $_POST['noindex_seo_form_scope'] ) ) : 'settings'; if ( ! in_array( $scope, array( 'general', 'settings' ), true ) ) { $scope = 'settings'; } $contexts = noindex_seo_get_contexts(); $directives = noindex_seo_get_directives(); // Fields that only work with HTTP headers. $header_only_contexts = array( 'attachment' ); // Start from the current consolidated settings so we only overwrite what // the form actually touches. The shape is preserved by noindex_seo_update_settings(). $settings = noindex_seo_get_settings(); if ( 'settings' === $scope ) { // The method select lives on the General tab, so the header-only // restriction follows the SAVED method, not the POST body. $saved_method = noindex_seo_get_config( 'method', 'meta' ); $is_header_enabled = in_array( $saved_method, array( 'header', 'both' ), true ); // Process directive grid: one entry per (context, directive). // Boolean directives arrive as '1' checkboxes; value directives as // their raw value (empty = off). Everything normalizes through // noindex_seo_normalize_directive_value(). // phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified above. foreach ( $contexts as $context ) { foreach ( $directives as $directive ) { $option_key = $directive . '_seo_' . $context; // Header-only contexts are forced off when headers aren't enabled. if ( in_array( $context, $header_only_contexts, true ) && ! $is_header_enabled ) { $settings['contexts'][ $context ][ $directive ] = in_array( $directive, noindex_seo_get_value_directives(), true ) ? '' : 0; continue; } $option_value = ( isset( $_POST[ $option_key ] ) && is_string( $_POST[ $option_key ] ) ) ? sanitize_text_field( wp_unslash( $_POST[ $option_key ] ) ) : ''; $settings['contexts'][ $context ][ $directive ] = noindex_seo_normalize_directive_value( $directive, $option_value ); } } // Conditional auto-noindex rules (3.6.0): parallel arrays of fields // and values from the rules table; each element sanitized inline. $raw_rules = array(); if ( isset( $_POST['noindex_seo_rule_field'], $_POST['noindex_seo_rule_value'] ) && is_array( $_POST['noindex_seo_rule_field'] ) && is_array( $_POST['noindex_seo_rule_value'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- array input; every element is sanitized in the loop below. $fields = (array) wp_unslash( $_POST['noindex_seo_rule_field'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- array input; every element is sanitized in the loop below. $values = (array) wp_unslash( $_POST['noindex_seo_rule_value'] ); foreach ( $values as $index => $rule_value ) { $field_raw = isset( $fields[ $index ] ) ? $fields[ $index ] : ''; $raw_rules[] = array( 'field' => is_scalar( $field_raw ) ? sanitize_text_field( wp_unslash( (string) $field_raw ) ) : '', 'value' => is_scalar( $rule_value ) ? sanitize_text_field( wp_unslash( (string) $rule_value ) ) : '', ); } } $settings['rules'] = noindex_seo_sanitize_rules( $raw_rules ); // phpcs:enable WordPress.Security.NonceVerification.Missing } else { // phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified above. // Get the implementation method to validate field compatibility. $method_value = ( isset( $_POST['noindex_seo_config_method'] ) && is_string( $_POST['noindex_seo_config_method'] ) ) ? sanitize_text_field( wp_unslash( $_POST['noindex_seo_config_method'] ) ) : 'meta'; // Validate method. $settings['config']['method'] = in_array( $method_value, array( 'meta', 'header', 'both' ), true ) ? $method_value : 'meta'; // Save general configuration values. $config_value = ( isset( $_POST['noindex_seo_config_seoplugins'] ) && is_string( $_POST['noindex_seo_config_seoplugins'] ) ) ? absint( $_POST['noindex_seo_config_seoplugins'] ) : 0; $settings['config']['seoplugins'] = ( 1 === $config_value ) ? 1 : 0; // Granular control. $granular_value = ( isset( $_POST['noindex_seo_config_granular'] ) && is_string( $_POST['noindex_seo_config_granular'] ) ) ? absint( $_POST['noindex_seo_config_granular'] ) : 0; $settings['config']['granular'] = ( 1 === $granular_value ) ? 1 : 0; // Per-term granular control on taxonomies. $tax_granular_value = ( isset( $_POST['noindex_seo_config_taxonomies_granular'] ) && is_string( $_POST['noindex_seo_config_taxonomies_granular'] ) ) ? absint( $_POST['noindex_seo_config_taxonomies_granular'] ) : 0; $settings['config']['taxonomies_granular'] = ( 1 === $tax_granular_value ) ? 1 : 0; // Delete-on-uninstall opt-in. $delete_value = ( isset( $_POST['noindex_seo_config_delete_on_uninstall'] ) && is_string( $_POST['noindex_seo_config_delete_on_uninstall'] ) ) ? absint( $_POST['noindex_seo_config_delete_on_uninstall'] ) : 0; $settings['config']['delete_on_uninstall'] = ( 1 === $delete_value ) ? 1 : 0; // phpcs:enable WordPress.Security.NonceVerification.Missing // Keep the header-only invariant consistent with the (possibly just // changed) method: attachment directives cannot survive a method // that does not send HTTP headers. $is_header_enabled = in_array( $settings['config']['method'], array( 'header', 'both' ), true ); if ( ! $is_header_enabled ) { foreach ( $directives as $directive ) { $settings['contexts']['attachment'][ $directive ] = in_array( $directive, noindex_seo_get_value_directives(), true ) ? '' : 0; } } } // Persist. This fires update_option_noindex_seo_settings, which clears the // transient via noindex_seo_invalidate_cache_on_settings_update() — so we // no longer need to delete_transient() by hand here. noindex_seo_update_settings( $settings ); wp_safe_redirect( admin_url( 'options-general.php?page=noindex_seo&tab=' . $scope . '&updated=true' ) ); exit; } add_action( 'admin_post_update_noindex_seo', 'noindex_seo_process_form' ); /** * Handles the "Apply recommended defaults" form action. * * Iterates the settings page section definitions and enables every boolean * directive for every context flagged `'suggestion' => true`. The 15 contexts * currently flagged are: privacy_policy, date, day, month, time, year, paged, * search, attachment, customize_preview, preview, error, woo_cart, * woo_checkout, woo_myaccount. * * All six boolean directives (noindex, nofollow, noarchive, nosnippet, * noimageindex, notranslate) are enabled on each suggested context — * value-carrying directives (3.6.0) are untouched because "enabling" them * without a value is meaningless. This is the same shape a manual * click-through would produce, so the form is fully editable afterwards. * * Hooked to the {@see 'admin_post_noindex_seo_apply_suggestions'} action. * * @since 3.0.0 * @since 3.1.5 Same nonce-verification split as noindex_seo_process_form(). * @since 3.3.0 Redirects back to the SEO Settings tab. * * @return void */ function noindex_seo_process_apply_suggestions() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Permission denied.', 'noindex-seo' ) ); } check_admin_referer( 'noindex_seo_apply_suggestions_nonce' ); $directives = noindex_seo_get_boolean_directives(); $settings = noindex_seo_get_settings(); foreach ( noindex_seo_get_suggested_contexts() as $context ) { foreach ( $directives as $directive ) { $settings['contexts'][ $context ][ $directive ] = 1; } } noindex_seo_update_settings( $settings ); wp_safe_redirect( admin_url( 'options-general.php?page=noindex_seo&tab=settings&suggestions_applied=1' ) ); exit; } add_action( 'admin_post_noindex_seo_apply_suggestions', 'noindex_seo_process_apply_suggestions' ); /** * Builds the JSON export payload for the current settings. * * The payload carries a plugin marker, an export timestamp and the full * consolidated settings array, so a backup can be identified and validated * on import. * * @since 3.2.0 * * @return array Export payload. */ function noindex_seo_build_export_payload() { return array( 'plugin' => 'noindex-seo', 'exported' => gmdate( 'c' ), 'settings' => noindex_seo_get_settings(), ); } /** * Handles the "Export settings" form action: streams the current settings * as a downloadable JSON file. * * Hooked to the {@see 'admin_post_noindex_seo_export'} action. * * @since 3.2.0 * * @return void */ function noindex_seo_handle_export() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Permission denied.', 'noindex-seo' ) ); } check_admin_referer( 'noindex_seo_export' ); nocache_headers(); header( 'Content-Type: application/json; charset=utf-8' ); header( 'Content-Disposition: attachment; filename=noindex-seo-settings-' . gmdate( 'Ymd-His' ) . '.json' ); echo wp_json_encode( noindex_seo_build_export_payload() ); exit; } add_action( 'admin_post_noindex_seo_export', 'noindex_seo_handle_export' ); /** * Validates and sanitizes a settings array that came from an imported * JSON file. * * Only contexts and directives currently known to the plugin are imported * (contexts for custom post types that do not exist on this site are * silently dropped); every directive value is normalized to 0/1 and every * config value to its safelisted form. The returned array always has the * full default shape of noindex_seo_get_settings(). * * @since 3.2.0 * @since 3.6.0 Value directives normalize through * noindex_seo_normalize_directive_value() and the conditional * rules are sanitized with noindex_seo_sanitize_rules(). * * @param mixed $raw Decoded JSON 'settings' value. * @return array{ * version: int, * contexts: array>, * rules: array, * config: array{ * method: string, * granular: int, * taxonomies_granular: int, * seoplugins: int, * delete_on_uninstall: int * } * }|null Sanitized settings array, or null when the payload is not importable. */ function noindex_seo_sanitize_imported_settings( $raw ) { if ( ! is_array( $raw ) || ! isset( $raw['contexts'], $raw['config'] ) || ! is_array( $raw['contexts'] ) || ! is_array( $raw['config'] ) ) { return null; } $settings = noindex_seo_get_settings(); $directives = noindex_seo_get_directives(); foreach ( noindex_seo_get_contexts() as $context ) { if ( ! isset( $raw['contexts'][ $context ] ) || ! is_array( $raw['contexts'][ $context ] ) ) { continue; } foreach ( $directives as $directive ) { if ( array_key_exists( $directive, $raw['contexts'][ $context ] ) && is_scalar( $raw['contexts'][ $context ][ $directive ] ) ) { $settings['contexts'][ $context ][ $directive ] = noindex_seo_normalize_directive_value( $directive, $raw['contexts'][ $context ][ $directive ] ); } } } if ( array_key_exists( 'rules', $raw ) ) { $settings['rules'] = noindex_seo_sanitize_rules( $raw['rules'] ); } $raw_config = $raw['config']; $method = isset( $raw_config['method'] ) && is_string( $raw_config['method'] ) ? $raw_config['method'] : 'meta'; $settings['config']['method'] = in_array( $method, array( 'meta', 'header', 'both' ), true ) ? $method : 'meta'; foreach ( array( 'granular', 'taxonomies_granular', 'seoplugins', 'delete_on_uninstall' ) as $key ) { $value = isset( $raw_config[ $key ] ) && is_numeric( $raw_config[ $key ] ) ? (int) $raw_config[ $key ] : 0; $settings['config'][ $key ] = ( 1 === $value ) ? 1 : 0; } return $settings; } /** * Handles the "Import settings" form action: reads an uploaded JSON backup * and restores the global settings from it. * * The upload is validated (error code, size limit, is_uploaded_file) and * never persisted to the uploads directory. Per-post and per-term granular * overrides are content data and are never touched by an import. * * Hooked to the {@see 'admin_post_noindex_seo_import'} action. * * @since 3.2.0 * @since 3.3.0 Redirects back to the Import / Export tab. * * @return void */ function noindex_seo_handle_import() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Permission denied.', 'noindex-seo' ) ); } check_admin_referer( 'noindex_seo_import' ); $redirect_error = admin_url( 'options-general.php?page=noindex_seo&tab=tools&import_error=1' ); // The upload is validated immediately below (error code, size, is_uploaded_file) and its // contents go through strict JSON shape validation before anything is persisted. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized $upload = isset( $_FILES['noindex_seo_import_file'] ) && is_array( $_FILES['noindex_seo_import_file'] ) ? $_FILES['noindex_seo_import_file'] // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized : array(); $error = isset( $upload['error'] ) && is_numeric( $upload['error'] ) ? (int) $upload['error'] : -1; $size = isset( $upload['size'] ) && is_numeric( $upload['size'] ) ? (int) $upload['size'] : 0; $tmp = isset( $upload['tmp_name'] ) && is_string( $upload['tmp_name'] ) ? $upload['tmp_name'] : ''; if ( UPLOAD_ERR_OK !== $error || '' === $tmp || $size > 1048576 || ! is_uploaded_file( $tmp ) ) { wp_safe_redirect( $redirect_error ); exit; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- reading the just-validated upload before it is discarded; is_uploaded_file() was checked above. $raw = file_get_contents( $tmp ); $data = is_string( $raw ) ? json_decode( $raw, true ) : null; if ( ! is_array( $data ) || 'noindex-seo' !== ( isset( $data['plugin'] ) ? $data['plugin'] : '' ) ) { wp_safe_redirect( $redirect_error ); exit; } $settings = noindex_seo_sanitize_imported_settings( isset( $data['settings'] ) ? $data['settings'] : null ); if ( null === $settings ) { wp_safe_redirect( $redirect_error ); exit; } noindex_seo_update_settings( $settings ); wp_safe_redirect( admin_url( 'options-general.php?page=noindex_seo&tab=tools&imported=1' ) ); exit; } add_action( 'admin_post_noindex_seo_import', 'noindex_seo_handle_import' ); /** * Applies a directive change to a context in the consolidated settings. * * Shared logic of the `wp noindex-seo set|unset` commands: validates the * context and the directives, enforces the header-only invariant for the * attachment context, persists via noindex_seo_update_settings() (which * also invalidates the transient cache) and reports what changed. * * Directive tokens are plain names for boolean directives (noindex, notranslate, * …) and `name=value` pairs for value directives (max-snippet=-1, * max-image-preview=large, unavailable_after=2030-01-01 09:00). Passing a * value for a boolean directive, or an invalid or missing value for a value * directive, is rejected with a descriptive error. * * @since 3.4.0 * @since 3.6.0 Value directives are supported via name=value tokens. * * @param string $context Context slug. * @param string[] $directives Directive tokens (names or name=value). * @param bool $enable True to enable, false to disable. * @return true|WP_Error True on success, WP_Error describing the first problem found. */ function noindex_seo_cli_apply_directives( $context, array $directives, $enable ) { if ( ! in_array( $context, noindex_seo_get_contexts(), true ) ) { return new WP_Error( 'noindex_seo_cli_unknown_context', sprintf( "Unknown context '%s'. Run 'wp noindex-seo list' to see the available contexts.", $context ) ); } $valid_directives = noindex_seo_get_directives(); $parsed = array(); foreach ( $directives as $token ) { $name = $token; $value = null; if ( false !== strpos( $token, '=' ) ) { $pieces = explode( '=', $token, 2 ); $name = $pieces[0]; $value = $pieces[1]; } if ( ! in_array( $name, $valid_directives, true ) ) { return new WP_Error( 'noindex_seo_cli_unknown_directive', sprintf( "Unknown directive '%s'. Valid directives: %s.", $name, implode( ', ', $valid_directives ) ) ); } if ( in_array( $name, noindex_seo_get_boolean_directives(), true ) ) { if ( null !== $value ) { return new WP_Error( 'noindex_seo_cli_unexpected_value', sprintf( "Directive '%s' does not take a value; pass just the name.", $name ) ); } $parsed[ $name ] = $enable ? 1 : 0; continue; } // Value directive: enabling requires a valid value; disabling clears it. if ( ! $enable ) { $parsed[ $name ] = ''; continue; } $normalized = noindex_seo_normalize_directive_value( $name, $value ); if ( null === $value || '' === $normalized ) { return new WP_Error( 'noindex_seo_cli_invalid_value', sprintf( "Invalid or missing value for '%s'. Use %s. Example: %s.", $name, 'max-snippet|max-video-preview' === $name ? 'an integer >= -1' : ( 'max-image-preview' === $name ? 'none, standard or large' : 'a date and time like 2030-01-01 09:00' ), 'max-snippet|max-video-preview' === $name ? 'max-snippet=-1' : ( 'max-image-preview' === $name ? 'max-image-preview=large' : 'unavailable_after=2030-01-01 09:00' ) ) ); } $parsed[ $name ] = $normalized; } // The attachment context only works with HTTP headers (same rule as the // settings page), so refuse enabling it under a meta-only method. $method = noindex_seo_get_config( 'method', 'meta' ); $method = is_string( $method ) ? $method : 'meta'; if ( $enable && 'attachment' === $context && ! in_array( $method, array( 'header', 'both' ), true ) ) { return new WP_Error( 'noindex_seo_cli_header_only', sprintf( "The attachment context only works with HTTP headers; the current implementation method is '%s'. Switch the method first: wp option update noindex_seo_settings ... or use the settings page.", $method ) ); } $settings = noindex_seo_get_settings(); foreach ( $parsed as $directive => $value ) { $settings['contexts'][ $context ][ $directive ] = $value; } noindex_seo_update_settings( $settings ); return true; } /** * Builds the rows for the `wp noindex-seo list` command. * * Boolean directives report on/off; value directives (3.6.0) report their * value (e.g. `max-snippet:-1`) or off. * * @since 3.4.0 * @since 3.6.0 Value directives report their configured value. * * @param string $context_filter Optional context slug to filter by. Empty for all. * @return array Rows. */ function noindex_seo_cli_get_rows( $context_filter = '' ) { $rows = array(); foreach ( noindex_seo_get_contexts() as $context ) { if ( '' !== $context_filter && $context !== $context_filter ) { continue; } foreach ( noindex_seo_get_directives() as $directive ) { $value = noindex_seo_get_setting( $context, $directive ); if ( in_array( $directive, noindex_seo_get_boolean_directives(), true ) ) { $status = $value ? 'on' : 'off'; } elseif ( '' === $value ) { $status = 'off'; } else { $status = noindex_seo_format_value_directive( $directive, (string) $value ); } $rows[] = array( 'context' => $context, 'directive' => $directive, 'status' => $status, ); } } return $rows; } /** * WP-CLI command: lists every context x directive pair and its status. * * ## OPTIONS * * [--only=] * : Only list the given context slug. * * [--format=] * : Render output in a particular format. * --- * default: table * options: * - table * - csv * - json * - yaml * --- * * ## EXAMPLES * * wp noindex-seo list * wp noindex-seo list --only=search --format=json * * @since 3.4.0 * @since 3.5.0 The filter parameter is `--only`: WP-CLI 2.11+ reserves the * global `--context` flag for its own context switching, so a * command parameter of that name never reaches the handler. * Output now goes through the namespaced format_items() * function — the real WP-CLI API (the static WP_CLI\Utils:: * format_items() call fatalled on every invocation). * * @param array $args Positional arguments (unused). * @param array $assoc_args Associative arguments. * @return void */ function noindex_seo_cli_list( $args, $assoc_args ) { $context_filter = ''; if ( isset( $assoc_args['only'] ) && is_string( $assoc_args['only'] ) && '' !== $assoc_args['only'] ) { // Validate the raw value against the known contexts: sanitize_key() // alone would silently turn an invalid value into '' and list everything. if ( ! in_array( $assoc_args['only'], noindex_seo_get_contexts(), true ) ) { WP_CLI::error( sprintf( "Unknown context '%s'. Run 'wp noindex-seo list' to see the available contexts.", $assoc_args['only'] ) ); return; } $context_filter = $assoc_args['only']; } $rows = noindex_seo_cli_get_rows( $context_filter ); $format = isset( $assoc_args['format'] ) && is_string( $assoc_args['format'] ) ? $assoc_args['format'] : 'table'; WP_CLI\Utils\format_items( $format, $rows, array( 'context', 'directive', 'status' ) ); } /** * WP-CLI command: enables directives on a context. * * ## OPTIONS * * * : Context slug (see `wp noindex-seo list`). * * [...] * : One or more directives to enable. Boolean directives by name * (noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate); * value directives as name=value (e.g. max-snippet=-1, * max-image-preview=large, unavailable_after="2030-01-01 09:00" — * datetimes need quoting because of the space, or a T separator: * unavailable_after=2030-01-01T09:00). Default: all six boolean directives. * * ## EXAMPLES * * wp noindex-seo set search noindex * wp noindex-seo set date noindex noarchive * wp noindex-seo set archive max-snippet=-1 max-image-preview=large * * @since 3.4.0 * @since 3.6.0 Value directives accepted as name=value tokens; notranslate * joined the boolean set. * * @param array $args [context, directive...]. * @param array $assoc_args Associative arguments (unused). * @return void */ function noindex_seo_cli_set( $args, $assoc_args ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- required by the WP-CLI callback signature if ( empty( $args ) ) { WP_CLI::error( 'Usage: wp noindex-seo set [...]' ); return; } $context = sanitize_key( (string) array_shift( $args ) ); $directives = noindex_seo_get_boolean_directives(); if ( ! empty( $args ) ) { // Not sanitize_key(): value tokens contain '=', and datetime values // contain ':' and '-'; noindex_seo_cli_apply_directives() validates. $directives = array_values( array_filter( array_map( 'trim', array_map( 'sanitize_text_field', $args ) ) ) ); } $result = noindex_seo_cli_apply_directives( $context, $directives, true ); if ( is_wp_error( $result ) ) { WP_CLI::error( $result->get_error_message() ); return; } WP_CLI::success( sprintf( "Enabled %s on '%s'.", implode( ', ', $directives ), $context ) ); } /** * WP-CLI command: disables directives on a context. * * ## OPTIONS * * * : Context slug (see `wp noindex-seo list`). * * [...] * : One or more directives to disable. Boolean directives by name; value * directives by plain name (max-snippet) — passing a value is not needed * to disable. Default: all six boolean directives. * * ## EXAMPLES * * wp noindex-seo unset search noindex * wp noindex-seo unset archive max-snippet * * @since 3.4.0 * @since 3.6.0 Value directives can be disabled by plain name. * * @param array $args [context, directive...]. * @param array $assoc_args Associative arguments (unused). * @return void */ function noindex_seo_cli_unset( $args, $assoc_args ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- required by the WP-CLI callback signature if ( empty( $args ) ) { WP_CLI::error( 'Usage: wp noindex-seo unset [...]' ); return; } $context = sanitize_key( (string) array_shift( $args ) ); $directives = noindex_seo_get_boolean_directives(); if ( ! empty( $args ) ) { $directives = array_values( array_filter( array_map( 'trim', array_map( 'sanitize_text_field', $args ) ) ) ); } $result = noindex_seo_cli_apply_directives( $context, $directives, false ); if ( is_wp_error( $result ) ) { WP_CLI::error( $result->get_error_message() ); return; } WP_CLI::success( sprintf( "Disabled %s on '%s'.", implode( ', ', $directives ), $context ) ); } /** * WP-CLI command: exports the settings as JSON. * * Writes the same payload as the "Export settings" button. * * ## OPTIONS * * [] * : Path of the JSON file to write. Default: print to STDOUT. * * ## EXAMPLES * * wp noindex-seo export > noindex-seo-backup.json * wp noindex-seo export backup.json * * @since 3.4.0 * * @param array $args []. * @param array $assoc_args Associative arguments (unused). * @return void */ function noindex_seo_cli_export( $args, $assoc_args ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- required by the WP-CLI callback signature $json = wp_json_encode( noindex_seo_build_export_payload() ); if ( false === $json ) { WP_CLI::error( 'Could not encode the settings as JSON.' ); return; } if ( empty( $args ) ) { WP_CLI::line( $json ); return; } $file = (string) $args[0]; $written = file_put_contents( $file, $json . "\n" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- CLI context, the path is operator-supplied. if ( false === $written ) { WP_CLI::error( sprintf( "Could not write to '%s'.", $file ) ); } WP_CLI::success( sprintf( "Exported settings to '%s'.", $file ) ); } /** * WP-CLI command: imports settings from a previously exported JSON file. * * Applies the same validation and sanitization as the "Import settings" * form; per-post and per-term overrides are never touched. * * ## OPTIONS * * * : Path of a JSON file produced by `wp noindex-seo export` or the tools tab. * * [--dry-run] * : Validate and report the number of values that would change, without saving. * * ## EXAMPLES * * wp noindex-seo import noindex-seo-backup.json --dry-run * wp noindex-seo import noindex-seo-backup.json * * @since 3.4.0 * * @param array $args []. * @param array $assoc_args Associative arguments. * @return void */ function noindex_seo_cli_import( $args, $assoc_args ) { if ( empty( $args ) ) { WP_CLI::error( 'Usage: wp noindex-seo import [--dry-run]' ); return; } $file = (string) $args[0]; if ( ! is_readable( $file ) ) { WP_CLI::error( sprintf( "Cannot read '%s'.", $file ) ); return; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- CLI context, local operator-supplied file, existence checked above. $raw = file_get_contents( $file ); $data = is_string( $raw ) ? json_decode( $raw, true ) : null; if ( ! is_array( $data ) ) { WP_CLI::error( sprintf( "'%s' is not a valid noindex SEO export.", $file ) ); return; } $marker = isset( $data['plugin'] ) && is_string( $data['plugin'] ) ? $data['plugin'] : ''; if ( 'noindex-seo' !== $marker ) { WP_CLI::error( sprintf( "'%s' is not a valid noindex SEO export.", $file ) ); return; } $settings = noindex_seo_sanitize_imported_settings( isset( $data['settings'] ) ? $data['settings'] : null ); if ( null === $settings ) { WP_CLI::error( sprintf( "'%s' does not contain valid settings.", $file ) ); return; } if ( isset( $assoc_args['dry-run'] ) ) { $current = noindex_seo_get_settings(); $changes = 0; foreach ( $settings['contexts'] as $context => $directives ) { foreach ( $directives as $directive => $value ) { if ( $current['contexts'][ $context ][ $directive ] !== $value ) { ++$changes; } } } foreach ( $settings['config'] as $key => $value ) { if ( $current['config'][ $key ] !== $value ) { ++$changes; } } WP_CLI::line( sprintf( 'Dry run: %d setting(s) would change. Re-run without --dry-run to apply.', $changes ) ); return; } noindex_seo_update_settings( $settings ); WP_CLI::success( 'Settings imported.' ); } /** * WP-CLI command: bulk per-post granular overrides. * * Scales beyond the ~200-post ceiling of the bulk UI: enables or disables * the robots override for the given post IDs, mirroring the "Enable / * Disable Robots Override" bulk actions. * * ## OPTIONS * * ... * : One or more post IDs. * * [--off] * : Disable the override (default: enable). Disabling also clears the * directive meta so the posts fall back to the global settings. * * ## EXAMPLES * * wp noindex-seo override 123 456 * wp noindex-seo override $(wp post list --post_type=page --field=ID) --off * * @since 3.4.0 * * @param array $args Post IDs. * @param array $assoc_args Associative arguments. * @return void */ function noindex_seo_cli_override( $args, $assoc_args ) { if ( empty( $args ) ) { WP_CLI::error( 'Usage: wp noindex-seo override ... [--off]' ); return; } $disable = isset( $assoc_args['off'] ); $done = 0; foreach ( $args as $raw_id ) { $post_id = (int) $raw_id; $post = get_post( $post_id ); if ( ! $post ) { WP_CLI::warning( sprintf( 'Skipping %d: post does not exist.', $post_id ) ); continue; } if ( $disable ) { delete_post_meta( $post_id, '_noindex_seo_override' ); noindex_seo_clear_post_directives( $post_id ); } else { update_post_meta( $post_id, '_noindex_seo_override', 1 ); } ++$done; } WP_CLI::success( sprintf( '%s override for %d post(s).', $disable ? 'Disabled' : 'Enabled', $done ) ); } // Register the WP-CLI commands only when running under WP-CLI. if ( defined( 'WP_CLI' ) && WP_CLI && class_exists( 'WP_CLI' ) ) { WP_CLI::add_command( 'noindex-seo list', 'noindex_seo_cli_list' ); WP_CLI::add_command( 'noindex-seo set', 'noindex_seo_cli_set' ); WP_CLI::add_command( 'noindex-seo unset', 'noindex_seo_cli_unset' ); WP_CLI::add_command( 'noindex-seo export', 'noindex_seo_cli_export' ); WP_CLI::add_command( 'noindex-seo import', 'noindex_seo_cli_import' ); WP_CLI::add_command( 'noindex-seo override', 'noindex_seo_cli_override' ); } /** * Returns the list of contexts flagged as suggested defaults on the settings page. * * Centralised so the "Apply recommended defaults" handler and any future * WP-CLI command share the same definition of "recommended". * * @since 3.0.0 * @since 3.5.0 Added the WooCommerce contexts (woo_cart, woo_checkout, * woo_myaccount); the suggested set grew from 12 to 15 contexts. * * @return string[] List of context slugs. */ function noindex_seo_get_suggested_contexts() { /** * Filter the contexts that the "Apply recommended defaults" button enables. * * Each returned slug MUST be one of the contexts declared by * noindex_seo_get_contexts(). Unknown slugs are silently ignored at the * call site. * * @since 3.0.0 * * @param string[] $suggested Context slugs flagged as recommended defaults. */ return apply_filters( 'noindex_seo_suggested_contexts', array( 'privacy_policy', 'date', 'day', 'month', 'time', 'year', 'paged', 'search', 'attachment', 'customize_preview', 'preview', 'error', 'woo_cart', 'woo_checkout', 'woo_myaccount', ) ); } /** * Register post meta for REST API and Gutenberg support. * * Registers all robots directive post meta fields with REST API support * to enable Gutenberg sidebar panel to read and write values. * * @since 2.0.0 * @since 3.1.3 Skipped on WordPress versions without register_post_meta() * (pre-4.9.6): granular control still works there through the * classic meta box, Quick Edit and bulk actions. * * @return void */ function noindex_seo_register_post_meta() { // Check if granular control is enabled. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( ! $granular_enabled ) { return; } if ( ! function_exists( 'register_post_meta' ) ) { return; } // Get all public post types. $post_types = get_post_types( array( 'public' => true ), 'names' ); // Meta fields to register. Boolean directives (and the override flag) are // integers; value directives (3.6.0) are strings normalized on write. $boolean_meta_fields = array( '_noindex_seo_override', '_noindex_seo_noindex', '_noindex_seo_nofollow', '_noindex_seo_noarchive', '_noindex_seo_nosnippet', '_noindex_seo_noimageindex', '_noindex_seo_notranslate', ); $value_meta_fields = array( '_noindex_seo_max-snippet', '_noindex_seo_max-image-preview', '_noindex_seo_max-video-preview', '_noindex_seo_unavailable_after', ); // Register each meta field for each post type. foreach ( $post_types as $post_type ) { foreach ( $boolean_meta_fields as $meta_key ) { register_post_meta( $post_type, $meta_key, array( 'show_in_rest' => true, 'single' => true, 'type' => 'integer', 'default' => 0, 'auth_callback' => function () { return current_user_can( 'edit_posts' ); }, ) ); } foreach ( $value_meta_fields as $meta_key ) { register_post_meta( $post_type, $meta_key, array( 'show_in_rest' => true, 'single' => true, 'type' => 'string', 'default' => '', 'sanitize_callback' => function ( $raw ) use ( $meta_key ) { return noindex_seo_normalize_directive_value( str_replace( '_noindex_seo_', '', $meta_key ), $raw ); }, 'auth_callback' => function () { return current_user_can( 'edit_posts' ); }, ) ); } } } add_action( 'init', 'noindex_seo_register_post_meta' ); /** * Register meta boxes for granular per-post/page control. * * Only registers meta boxes if granular control is enabled in settings. * Adds meta box to all public post types (posts, pages, custom post types). * * @since 2.0.0 * * @return void */ function noindex_seo_add_meta_boxes() { // Check if granular control is enabled. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( ! $granular_enabled ) { return; } // Skip the classic meta box when the current request is using the block // editor — the native PluginDocumentSettingPanel registered by // assets/js/editor-sidebar.js handles those cases. Registering the classic // meta box as well caused two panels with the same "Search Engine // Visibility" title to render in the block editor (visible since WP 5.0, // reported as jarring on WP 7.1 — see 3.0.2 fix). // // We check the per-request screen flag (not the per-post-type default) // so the Classic Editor plugin's "?classic-editor" override still gets // the classic meta box when the user opens a block-editor post type in // classic mode. $screen = get_current_screen(); if ( $screen && version_compare( get_bloginfo( 'version' ), '5.0', '>=' ) && $screen->is_block_editor ) { return; } // Get all public post types. $post_types = get_post_types( array( 'public' => true ), 'names' ); // Add meta box to each public post type. foreach ( $post_types as $post_type ) { add_meta_box( 'noindex_seo_meta_box', __( 'Search Engine Visibility', 'noindex-seo' ), 'noindex_seo_render_meta_box', $post_type, 'side', 'default' ); } } add_action( 'add_meta_boxes', 'noindex_seo_add_meta_boxes' ); /** * Render the meta box content for per-post/page control. * * Displays a checkbox to override global settings and 5 directive checkboxes. * Shows current global settings as reference. * * @since 2.0.0 * * @param WP_Post $post The current post object. * @return void */ function noindex_seo_render_meta_box( WP_Post $post ) { // Add nonce for security. wp_nonce_field( 'noindex_seo_meta_box', 'noindex_seo_meta_box_nonce' ); // Get current post meta values. $override = get_post_meta( $post->ID, '_noindex_seo_override', true ); $noindex = get_post_meta( $post->ID, '_noindex_seo_noindex', true ); $nofollow = get_post_meta( $post->ID, '_noindex_seo_nofollow', true ); $noarchive = get_post_meta( $post->ID, '_noindex_seo_noarchive', true ); $nosnippet = get_post_meta( $post->ID, '_noindex_seo_nosnippet', true ); $noimageindex = get_post_meta( $post->ID, '_noindex_seo_noimageindex', true ); $notranslate = get_post_meta( $post->ID, '_noindex_seo_notranslate', true ); $max_snippet = get_post_meta( $post->ID, '_noindex_seo_max-snippet', true ); $max_image_preview = get_post_meta( $post->ID, '_noindex_seo_max-image-preview', true ); $max_video_preview = get_post_meta( $post->ID, '_noindex_seo_max-video-preview', true ); $unavailable_after = get_post_meta( $post->ID, '_noindex_seo_unavailable_after', true ); // Normalize the value directives for display. $max_snippet = noindex_seo_normalize_directive_value( 'max-snippet', $max_snippet ); $max_image_preview = noindex_seo_normalize_directive_value( 'max-image-preview', $max_image_preview ); $max_video_preview = noindex_seo_normalize_directive_value( 'max-video-preview', $max_video_preview ); $unavailable_after = noindex_seo_normalize_directive_value( 'unavailable_after', $unavailable_after ); // Get global settings for reference. $global_directives = array(); // Determine which context applies to this post type. $post_type = get_post_type( $post ); $context = ( 'page' === $post_type ) ? 'page' : 'single'; $global_map = noindex_seo_get_context_directives_map( $context ); foreach ( noindex_seo_format_directives( $global_map ) as $token ) { $global_directives[] = $token; } ?>

ID ) ); ?>



true ), 'names' ); $boolean_meta_keys = array( '_noindex_seo_override', '_noindex_seo_noindex', '_noindex_seo_nofollow', '_noindex_seo_noarchive', '_noindex_seo_nosnippet', '_noindex_seo_noimageindex', '_noindex_seo_notranslate', ); $value_meta_keys = array( '_noindex_seo_max-snippet', '_noindex_seo_max-image-preview', '_noindex_seo_max-video-preview', '_noindex_seo_unavailable_after', ); foreach ( $taxonomies as $taxonomy ) { foreach ( $boolean_meta_keys as $meta_key ) { register_term_meta( $taxonomy, $meta_key, array( 'show_in_rest' => true, 'single' => true, 'type' => 'integer', 'default' => 0, 'auth_callback' => static function () { return current_user_can( 'manage_categories' ); }, ) ); } foreach ( $value_meta_keys as $meta_key ) { register_term_meta( $taxonomy, $meta_key, array( 'show_in_rest' => true, 'single' => true, 'type' => 'string', 'default' => '', 'sanitize_callback' => function ( $raw ) use ( $meta_key ) { return noindex_seo_normalize_directive_value( str_replace( '_noindex_seo_', '', $meta_key ), $raw ); }, 'auth_callback' => static function () { return current_user_can( 'manage_categories' ); }, ) ); } // Render the form fields on the Edit Tag screen. add_action( "{$taxonomy}_edit_form_fields", 'noindex_seo_render_term_form_fields' ); // Persist the values when the term is updated. add_action( "edited_{$taxonomy}", 'noindex_seo_save_term_meta', 10, 2 ); } } add_action( 'init', 'noindex_seo_register_term_meta' ); /** * Renders the "Search Engine Visibility" panel on the Edit Term screen. * * Hooked to `{$taxonomy}_edit_form_fields` for every public taxonomy by * {@see noindex_seo_register_term_meta()}. Renders the same six controls as * the post meta box: one override checkbox and five directive checkboxes. * * @since 3.0.2 * @since 3.1.3 No-ops on WordPress versions without term meta (pre-4.4). * * @param WP_Term $term The term being edited. * @return void */ function noindex_seo_render_term_form_fields( WP_Term $term ) { if ( ! function_exists( 'get_term_meta' ) ) { return; } wp_nonce_field( 'noindex_seo_term_meta', 'noindex_seo_term_meta_nonce' ); $override_raw = get_term_meta( $term->term_id, '_noindex_seo_override', true ); $override = ( is_numeric( $override_raw ) ? (int) $override_raw : 0 ) ? 1 : 0; $values = array(); foreach ( noindex_seo_get_boolean_directives() as $directive ) { $raw_value = get_term_meta( $term->term_id, '_noindex_seo_' . $directive, true ); $values[ $directive ] = ( is_numeric( $raw_value ) ? (int) $raw_value : 0 ) ? 1 : 0; } foreach ( noindex_seo_get_value_directives() as $directive ) { $raw_value = get_term_meta( $term->term_id, '_noindex_seo_' . $directive, true ); $values[ $directive ] = is_scalar( $raw_value ) ? noindex_seo_normalize_directive_value( $directive, $raw_value ) : ''; } ?>

$columns Existing columns. * @return array Modified columns. */ function noindex_seo_add_custom_column( array $columns ) { // Check if granular control is enabled. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( ! $granular_enabled ) { return $columns; } // Insert column after title (or at the end if title doesn't exist). $new_columns = array(); foreach ( $columns as $key => $value ) { $new_columns[ $key ] = $value; if ( 'title' === $key ) { $new_columns['noindex_seo_directives'] = __( 'Robots', 'noindex-seo' ); } } // If title column doesn't exist, add at the end. if ( ! isset( $new_columns['noindex_seo_directives'] ) ) { $new_columns['noindex_seo_directives'] = __( 'Robots', 'noindex-seo' ); } return $new_columns; } /** * Display content of custom robots directives column. * * @since 2.0.0 * * @param string $column Column name. * @param int $post_id Post ID. * @return void */ function noindex_seo_display_custom_column( $column, $post_id ) { if ( 'noindex_seo_directives' !== $column ) { return; } $override = get_post_meta( $post_id, '_noindex_seo_override', true ); // Collect directive values for Quick Edit: booleans as 0/1, value // directives as their normalized string ('' = off). $directives_values = array( 'override' => ( is_scalar( $override ) ? absint( $override ) : 0 ), ); $directive_map = array(); foreach ( noindex_seo_get_boolean_directives() as $directive ) { $meta_value = get_post_meta( $post_id, '_noindex_seo_' . $directive, true ); $directives_values[ $directive ] = ( is_scalar( $meta_value ) && 1 === absint( $meta_value ) ) ? 1 : 0; if ( 1 === $directives_values[ $directive ] ) { $directive_map[ $directive ] = true; } } foreach ( noindex_seo_get_value_directives() as $directive ) { $meta_value = get_post_meta( $post_id, '_noindex_seo_' . $directive, true ); $value = is_scalar( $meta_value ) ? noindex_seo_normalize_directive_value( $directive, $meta_value ) : ''; $directives_values[ $directive ] = $value; if ( '' !== $value ) { $directive_map[ $directive ] = $value; } } // Output hidden data for Quick Edit to read. echo ''; if ( ! $override ) { echo '—'; return; } if ( empty( $directive_map ) ) { echo '' . esc_html__( 'Override (none)', 'noindex-seo' ) . ''; return; } // Display active directives as badges (booleans as names, value // directives as name:value tokens). $tokens = noindex_seo_format_directives( $directive_map ); echo '
'; foreach ( $tokens as $token ) { $badge_directive = ( false === strpos( $token, ':' ) ) ? $token : substr( $token, 0, strpos( $token, ':' ) ); echo ''; echo noindex_seo_get_directive_icon_html( $badge_directive ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. echo ' ' . esc_html( $token ); echo ''; } echo '
'; } // Register column hooks after all CPTs are registered (admin_init fires after init). add_action( 'admin_init', function () { $post_types = get_post_types( array( 'public' => true ), 'names' ); foreach ( $post_types as $post_type ) { add_filter( "manage_{$post_type}_posts_columns", 'noindex_seo_add_custom_column' ); add_action( "manage_{$post_type}_posts_custom_column", 'noindex_seo_display_custom_column', 10, 2 ); } // Mirror the Robots column on taxonomy list tables when per-term // granular control is on, so admins can see at a glance which terms // have an override the same way they can for posts. if ( noindex_seo_get_config( 'taxonomies_granular', 0 ) ) { $taxonomies = get_taxonomies( array( 'public' => true ), 'names' ); foreach ( $taxonomies as $taxonomy ) { add_filter( "manage_edit-{$taxonomy}_columns", 'noindex_seo_add_term_custom_column' ); add_filter( "manage_{$taxonomy}_custom_column", 'noindex_seo_display_term_custom_column', 10, 3 ); } } } ); /** * Adds the "Robots" column to taxonomy list tables. * * Term-meta counterpart of {@see noindex_seo_add_custom_column()}. * * @since 3.0.2 * * @param array $columns Existing columns. * @return array Modified columns. */ function noindex_seo_add_term_custom_column( array $columns ) { $new_columns = array(); foreach ( $columns as $key => $value ) { $new_columns[ $key ] = $value; // Insert after the name column (the first one on term list tables). if ( 'name' === $key ) { $new_columns['noindex_seo_directives'] = __( 'Robots', 'noindex-seo' ); } } // Fallback: add at the end if the name column wasn't found. if ( ! isset( $new_columns['noindex_seo_directives'] ) ) { $new_columns['noindex_seo_directives'] = __( 'Robots', 'noindex-seo' ); } return $new_columns; } /** * Displays the Robots column content on taxonomy list tables. * * Renders the same emoji + directive badges as the post column so the UX is * consistent across post-type and taxonomy list tables. Shows an em dash when * the term has no override. * * Term-meta counterpart of {@see noindex_seo_display_custom_column()}. * * @since 3.0.2 * * @param string $content Existing column content (filter hook signature). * @param string $column Column name. * @param int $term_id Term ID. * @return string Filtered content. */ function noindex_seo_display_term_custom_column( $content, $column, $term_id ) { if ( 'noindex_seo_directives' !== $column ) { return $content; } // Term meta requires WordPress 4.4+. if ( ! function_exists( 'get_term_meta' ) ) { return $content; } $override_raw = get_term_meta( $term_id, '_noindex_seo_override', true ); $override = ( is_scalar( $override_raw ) && 1 === absint( $override_raw ) ) ? 1 : 0; if ( ! $override ) { return '—'; } $term_map = array(); foreach ( noindex_seo_get_boolean_directives() as $directive ) { $value = get_term_meta( $term_id, '_noindex_seo_' . $directive, true ); if ( is_scalar( $value ) && 1 === absint( $value ) ) { $term_map[ $directive ] = true; } } foreach ( noindex_seo_get_value_directives() as $directive ) { $raw = get_term_meta( $term_id, '_noindex_seo_' . $directive, true ); $value = is_scalar( $raw ) ? noindex_seo_normalize_directive_value( $directive, $raw ) : ''; if ( '' !== $value ) { $term_map[ $directive ] = $value; } } if ( empty( $term_map ) ) { return '' . esc_html__( 'Override (none)', 'noindex-seo' ) . ''; } $tokens = noindex_seo_format_directives( $term_map ); $out = '
'; foreach ( $tokens as $token ) { $badge_directive = ( false === strpos( $token, ':' ) ) ? $token : substr( $token, 0, strpos( $token, ':' ) ); $out .= ''; $out .= noindex_seo_get_directive_icon_html( $badge_directive ); // SVG from the plugin's own icon registry, or the escaped emoji fallback. $out .= ' ' . esc_html( $token ); $out .= ''; } $out .= '
'; return $out; } /** * Add Quick Edit fields for robots directives. * * Displays the same directive checkboxes in Quick Edit interface. * * @since 2.0.0 * * @param string $column_name Column name. * @param string $post_type Post type (unused but required by hook). * @return void */ function noindex_seo_quick_edit_fields( $column_name, $post_type ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed // Check if granular control is enabled. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( ! $granular_enabled ) { return; } if ( 'noindex_seo_directives' !== $column_name ) { return; } // Add nonce field. wp_nonce_field( 'noindex_seo_quick_edit', 'noindex_seo_quick_edit_nonce' ); ?>
$bulk_actions Existing bulk actions. * @return array Modified bulk actions. */ function noindex_seo_register_bulk_actions( array $bulk_actions ) { // Check if granular control is enabled. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( ! $granular_enabled ) { return $bulk_actions; } $bulk_actions['noindex_seo_enable_override'] = __( 'Enable Robots Override', 'noindex-seo' ); $bulk_actions['noindex_seo_disable_override'] = __( 'Disable Robots Override', 'noindex-seo' ); return $bulk_actions; } /** * Handle custom bulk actions for robots directives. * * @since 2.0.0 * * @param string $redirect_to Redirect URL. * @param string $action Action being taken. * @param array $post_ids Array of post IDs. * @return string Modified redirect URL. */ function noindex_seo_handle_bulk_actions( $redirect_to, $action, array $post_ids ) { // Check if granular control is enabled. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( ! $granular_enabled ) { return $redirect_to; } // Validate that we have post IDs to process. if ( empty( $post_ids ) ) { return $redirect_to; } // Check user permissions - user must be able to edit posts. if ( ! current_user_can( 'edit_posts' ) ) { return $redirect_to; } // Filter post IDs to only include ones the current user can edit. $editable_post_ids = array(); foreach ( $post_ids as $post_id ) { $post_id = intval( $post_id ); if ( $post_id > 0 && current_user_can( 'edit_post', $post_id ) ) { $editable_post_ids[] = $post_id; } } // If no editable posts remain after filtering, return early. if ( empty( $editable_post_ids ) ) { return $redirect_to; } // Replace original post IDs with filtered list. $post_ids = $editable_post_ids; if ( 'noindex_seo_enable_override' === $action ) { // Use update_post_meta() — the WP postmeta table has no unique key on // (post_id, meta_key), so a raw INSERT ... ON DUPLICATE KEY UPDATE would // silently create duplicate rows on every bulk run. update_post_meta() // correctly handles the single-value semantics enforced by registered meta. foreach ( $post_ids as $post_id ) { update_post_meta( $post_id, '_noindex_seo_override', 1 ); } $redirect_to = add_query_arg( 'noindex_seo_bulk_enabled', count( $post_ids ), $redirect_to ); } if ( 'noindex_seo_disable_override' === $action ) { // Remove the override flag entirely and clear any directive meta so the // post falls back to the global context settings. foreach ( $post_ids as $post_id ) { delete_post_meta( $post_id, '_noindex_seo_override' ); noindex_seo_clear_post_directives( $post_id ); } $redirect_to = add_query_arg( 'noindex_seo_bulk_disabled', count( $post_ids ), $redirect_to ); } return $redirect_to; } /** * Display admin notice after bulk actions. * * @since 2.0.0 * * @return void */ function noindex_seo_bulk_actions_admin_notice() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL parameter from redirect after bulk action, not form data. if ( ! empty( $_REQUEST['noindex_seo_bulk_enabled'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL parameter from redirect after bulk action, not form data. $count = is_scalar( $_REQUEST['noindex_seo_bulk_enabled'] ) ? absint( $_REQUEST['noindex_seo_bulk_enabled'] ) : 0; printf( '

%s

', esc_html( sprintf( /* translators: %d: Number of posts updated */ _n( 'Robots override enabled for %d post.', 'Robots override enabled for %d posts.', $count, 'noindex-seo' ), $count ) ) ); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL parameter from redirect after bulk action, not form data. if ( ! empty( $_REQUEST['noindex_seo_bulk_disabled'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL parameter from redirect after bulk action, not form data. $count = is_scalar( $_REQUEST['noindex_seo_bulk_disabled'] ) ? absint( $_REQUEST['noindex_seo_bulk_disabled'] ) : 0; printf( '

%s

', esc_html( sprintf( /* translators: %d: Number of posts updated */ _n( 'Robots override disabled for %d post.', 'Robots override disabled for %d posts.', $count, 'noindex-seo' ), $count ) ) ); } } add_action( 'admin_notices', 'noindex_seo_bulk_actions_admin_notice' ); // Register bulk action hooks after all CPTs are registered. add_action( 'admin_init', function () { $post_types = get_post_types( array( 'public' => true ), 'names' ); foreach ( $post_types as $post_type ) { add_filter( "bulk_actions-edit-{$post_type}", 'noindex_seo_register_bulk_actions' ); add_filter( "handle_bulk_actions-edit-{$post_type}", 'noindex_seo_handle_bulk_actions', 10, 3 ); } } ); /** * Add filter dropdown to post list for robots override status. * * Allows filtering posts by override status: all, with override, without override. * * @since 2.0.0 * * @param string $post_type Current post type (unused but required by hook). * @return void */ function noindex_seo_add_list_filter( $post_type ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found // Check if granular control is enabled. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( ! $granular_enabled ) { return; } // Get current filter value from URL parameters (not a form submission, no nonce needed). // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL parameter for filtering, not form data. $current_filter = ( isset( $_GET['noindex_seo_filter'] ) && is_string( $_GET['noindex_seo_filter'] ) ) ? sanitize_text_field( wp_unslash( $_GET['noindex_seo_filter'] ) ) : ''; ?> is_main_query() ) { return; } // Check if granular control is enabled. $granular_enabled = noindex_seo_get_config( 'granular', 0 ); if ( ! $granular_enabled ) { return; } // Check if filter is set (URL parameter, not form submission, no nonce needed). // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL parameter for filtering, not form data. if ( ! isset( $_GET['noindex_seo_filter'] ) || empty( $_GET['noindex_seo_filter'] ) ) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL parameter for filtering, not form data. $filter = is_string( $_GET['noindex_seo_filter'] ) ? sanitize_text_field( wp_unslash( $_GET['noindex_seo_filter'] ) ) : ''; // Validate against whitelist of allowed filter values. $valid_filters = array( 'with_override', 'without_override' ); if ( ! in_array( $filter, $valid_filters, true ) ) { return; // Invalid filter value, ignore. } // Build meta query. $meta_query = array(); if ( 'with_override' === $filter ) { $meta_query = array( array( 'key' => '_noindex_seo_override', 'value' => '1', 'compare' => '=', ), ); } elseif ( 'without_override' === $filter ) { $meta_query = array( 'relation' => 'OR', array( 'key' => '_noindex_seo_override', 'value' => '1', 'compare' => '!=', ), array( 'key' => '_noindex_seo_override', 'compare' => 'NOT EXISTS', ), ); } $query->set( 'meta_query', $meta_query ); } add_action( 'pre_get_posts', 'noindex_seo_filter_posts_by_override' ); // Register filter dropdown after all CPTs are registered. add_action( 'admin_init', function () { $post_types = get_post_types( array( 'public' => true ), 'names' ); foreach ( $post_types as $post_type ) { add_action( 'restrict_manage_posts', function () use ( $post_type ) { global $typenow; if ( $typenow === $post_type ) { noindex_seo_add_list_filter( $post_type ); } } ); } } ); /** * Renders the settings page for the 'noindex SEO' plugin. * * The page uses the native WordPress tab navigation (`nav-tab-wrapper` / * `nav-tab`, the same pattern as the core Updates and Plugins screens): * URL-based switching via the `tab` query parameter, with the active * panel rendered server-side. No custom tab CSS or JavaScript. * * Tabs: * - general: implementation method and general configuration options. * - settings: the directive grid (contexts x directives) with stats, * search and the "Apply Recommended Defaults" action. * - tools: the JSON export / import forms. * * @since 1.0.0 * @since 2.0.0 Completely redesigned with modern UI/UX. * @since 3.3.0 Reorganized into native WordPress nav tabs; the form * handler became tab-scoped so saving one tab never * resets the values of the other. * * @return void */ function noindex_seo_admin() { // Verify user capabilities for defense in depth.. if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'noindex-seo' ), esc_html__( 'Permission Denied', 'noindex-seo' ), array( 'response' => 403 ) ); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only navigation state, not form data. $current_tab = isset( $_GET['tab'] ) && is_string( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'general'; if ( ! in_array( $current_tab, array( 'general', 'settings', 'tools' ), true ) ) { $current_tab = 'general'; } $tabs = array( 'general' => __( 'General', 'noindex-seo' ), 'settings' => __( 'SEO Settings', 'noindex-seo' ), 'tools' => __( 'Import / Export', 'noindex-seo' ), ); // Define section icons (using Dashicons).. $section_icons = array( 'main_pages' => 'dashicons-admin-home', 'pages_posts' => 'dashicons-admin-page', 'taxonomies' => 'dashicons-category', 'dates' => 'dashicons-calendar-alt', 'archives' => 'dashicons-archive', 'pagination' => 'dashicons-ellipsis', 'search' => 'dashicons-search', 'attachments' => 'dashicons-paperclip', 'previews' => 'dashicons-visibility', 'error_page' => 'dashicons-warning', ); // Define sections and their respective settings.. $sections = array( 'main_pages' => array( 'title' => __( 'Main Pages', 'noindex-seo' ), 'fields' => array( 'front_page' => array( 'label' => __( 'Front Page', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of the site\'s front page.', 'noindex-seo' ), 'view_url' => get_site_url(), ), 'home' => array( 'label' => __( 'Home', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of the site\'s home page.', 'noindex-seo' ), 'view_url' => get_home_url(), ), ), ), 'pages_posts' => array( 'title' => __( 'Pages and Posts', 'noindex-seo' ), 'fields' => array( 'page' => array( 'label' => __( 'Page', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of site pages.', 'noindex-seo' ), ), 'privacy_policy' => array( 'label' => __( 'Privacy Policy', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of the privacy policy page.', 'noindex-seo' ), 'view_url' => function_exists( 'get_privacy_policy_url' ) ? get_privacy_policy_url() : '', ), 'single' => array( 'label' => __( 'Single Post', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of individual posts.', 'noindex-seo' ), ), 'singular' => array( 'label' => __( 'Singular', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of any singular content (post or page).', 'noindex-seo' ), ), ), ), 'taxonomies' => array( 'title' => __( 'Taxonomies', 'noindex-seo' ), 'fields' => array( 'category' => array( 'label' => __( 'Category', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of category archive pages.', 'noindex-seo' ), ), 'tag' => array( 'label' => __( 'Tag', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of tag archive pages.', 'noindex-seo' ), ), ), ), 'dates' => array( 'title' => __( 'Date Archives', 'noindex-seo' ), 'fields' => array( 'date' => array( 'label' => __( 'Date', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of any date-based archive page.', 'noindex-seo' ), ), 'day' => array( 'label' => __( 'Day', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of daily archive pages.', 'noindex-seo' ), ), 'month' => array( 'label' => __( 'Month', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of monthly archive pages.', 'noindex-seo' ), ), 'time' => array( 'label' => __( 'Time', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of time-based archive pages.', 'noindex-seo' ), ), 'year' => array( 'label' => __( 'Year', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of yearly archive pages.', 'noindex-seo' ), ), ), ), 'archives' => array( 'title' => __( 'Archives', 'noindex-seo' ), 'fields' => array( 'archive' => array( 'label' => __( 'Archive', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of any type of archive page.', 'noindex-seo' ), ), 'author' => array( 'label' => __( 'Author', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of author archive pages.', 'noindex-seo' ), ), 'post_type_archive' => array( 'label' => __( 'Post Type Archive', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, 'description' => __( 'Block the indexing of post type archive pages.', 'noindex-seo' ), ), ), ), 'pagination' => array( 'title' => __( 'Pagination', 'noindex-seo' ), 'fields' => array( 'paged' => array( 'label' => __( 'Paginated Pages', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of pagination pages (page 2, 3, etc.).', 'noindex-seo' ), ), ), ), 'search' => array( 'title' => __( 'Search', 'noindex-seo' ), 'fields' => array( 'search' => array( 'label' => __( 'Search Results', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of search result pages.', 'noindex-seo' ), ), ), ), 'attachments' => array( 'title' => __( 'Attachments', 'noindex-seo' ), 'fields' => array( 'attachment' => array( 'label' => __( 'Attachment Pages', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of attachment pages (does not affect the file itself).', 'noindex-seo' ), ), ), ), 'previews' => array( 'title' => __( 'Previews', 'noindex-seo' ), 'fields' => array( 'customize_preview' => array( 'label' => __( 'Customize Preview', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing when content is in customize preview mode.', 'noindex-seo' ), ), 'preview' => array( 'label' => __( 'Post Preview', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing when viewing post previews.', 'noindex-seo' ), ), ), ), 'error_page' => array( 'title' => __( 'Error Pages', 'noindex-seo' ), 'fields' => array( 'error' => array( 'label' => __( 'Error 404', 'noindex-seo' ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => __( 'Block the indexing of 404 error pages.', 'noindex-seo' ), ), ), ), ); // Append a section listing every public custom post type with its own // directive grid. Each CPT becomes a row stored under the `cpt_{post_type}` // context. Built-in post / page / attachment are skipped (they have their // own dedicated contexts: single, page, attachment). $public_cpts = get_post_types( array( 'public' => true, '_builtin' => false, ), 'objects' ); if ( ! empty( $public_cpts ) ) { $cpt_fields = array(); foreach ( $public_cpts as $cpt ) { $cpt_fields[ 'cpt_' . $cpt->name ] = array( 'label' => noindex_seo_get_cpt_label( $cpt ), 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => false, /* translators: %s: post type singular name. */ 'description' => sprintf( __( 'Block the indexing of individual %s.', 'noindex-seo' ), noindex_seo_get_cpt_label( $cpt ) ), ); } $sections['custom_post_types'] = array( 'title' => __( 'Custom Post Types', 'noindex-seo' ), 'fields' => $cpt_fields, ); $section_icons['custom_post_types'] = 'dashicons-admin-post'; } // Append a WooCommerce section when the store's special pages are // configured (the page-ID options only exist when WooCommerce set them). // Cart / Checkout / My Account are regular pages that conventionally // deserve noindex but would otherwise fall into the generic 'page' bucket. // Built once, outside the loop: the three label sets cover every context. $woo_labels = array( 'woo_cart' => array( 'label' => __( 'Cart', 'noindex-seo' ), 'description' => __( 'Block the indexing of the WooCommerce cart page.', 'noindex-seo' ), ), 'woo_checkout' => array( 'label' => __( 'Checkout', 'noindex-seo' ), 'description' => __( 'Block the indexing of the WooCommerce checkout page.', 'noindex-seo' ), ), 'woo_myaccount' => array( 'label' => __( 'My Account', 'noindex-seo' ), 'description' => __( 'Block the indexing of the WooCommerce customer account pages (including order history and address endpoints).', 'noindex-seo' ), ), ); $woo_fields = array(); foreach ( noindex_seo_get_woo_context_options() as $woo_context => $woo_option ) { $woo_page_id = get_option( $woo_option, 0 ); if ( ! is_numeric( $woo_page_id ) || (int) $woo_page_id < 1 ) { continue; } $woo_fields[ $woo_context ] = array( 'label' => $woo_labels[ $woo_context ]['label'], 'recommended' => __( 'Recommended', 'noindex-seo' ), 'suggestion' => true, 'description' => $woo_labels[ $woo_context ]['description'], 'view_url' => get_permalink( (int) $woo_page_id ), ); } if ( ! empty( $woo_fields ) ) { $sections['woocommerce'] = array( 'title' => __( 'WooCommerce', 'noindex-seo' ), 'fields' => $woo_fields, ); $section_icons['woocommerce'] = 'dashicons-cart'; } // Get config options with explicit type narrowing. $opt_seoplugins = noindex_seo_get_config( 'seoplugins', 0 ); $option_config_seoplugins = is_scalar( $opt_seoplugins ) ? absint( $opt_seoplugins ) : 0; $opt_method = noindex_seo_get_config( 'method', 'meta' ); $option_config_method = is_string( $opt_method ) ? $opt_method : 'meta'; $opt_granular = noindex_seo_get_config( 'granular', 0 ); $option_config_granular = is_scalar( $opt_granular ) ? absint( $opt_granular ) : 0; $opt_tax_granular = noindex_seo_get_config( 'taxonomies_granular', 0 ); $option_config_taxonomies_granular = is_scalar( $opt_tax_granular ) ? absint( $opt_tax_granular ) : 0; $opt_delete = noindex_seo_get_config( 'delete_on_uninstall', 0 ); $option_config_delete_on_uninstall = is_scalar( $opt_delete ) ? absint( $opt_delete ) : 0; // Define fields that only work with HTTP headers (non-HTML content). $header_only_fields = array( 'attachment' ); $is_header_enabled = in_array( $option_config_method, array( 'header', 'both' ), true ); // Define available directives with config. 'type' drives the grid cell: // bool = checkbox, int = number input, preview = size select, // datetime = datetime-local input. Empty value = off. $directives_config = array( 'noindex' => array( 'label' => __( 'noindex', 'noindex-seo' ), 'desc' => __( 'Prevent search engines from indexing this page', 'noindex-seo' ), 'type' => 'bool', ), 'nofollow' => array( 'label' => __( 'nofollow', 'noindex-seo' ), 'desc' => __( 'Prevent search engines from following links on this page', 'noindex-seo' ), 'type' => 'bool', ), 'noarchive' => array( 'label' => __( 'noarchive', 'noindex-seo' ), 'desc' => __( 'Prevent search engines from showing a cached version', 'noindex-seo' ), 'type' => 'bool', ), 'nosnippet' => array( 'label' => __( 'nosnippet', 'noindex-seo' ), 'desc' => __( 'Prevent search engines from showing text snippets', 'noindex-seo' ), 'type' => 'bool', ), 'noimageindex' => array( 'label' => __( 'noimageindex', 'noindex-seo' ), 'desc' => __( 'Prevent search engines from indexing images', 'noindex-seo' ), 'type' => 'bool', ), 'notranslate' => array( 'label' => __( 'notranslate', 'noindex-seo' ), 'desc' => __( 'Ask search engines not to translate this page', 'noindex-seo' ), 'type' => 'bool', ), 'max-snippet' => array( 'label' => __( 'max-snippet', 'noindex-seo' ), 'desc' => __( 'Maximum snippet length in characters (-1 = no limit)', 'noindex-seo' ), 'type' => 'int', ), 'max-image-preview' => array( 'label' => __( 'max-image-preview', 'noindex-seo' ), 'desc' => __( 'Maximum image preview size', 'noindex-seo' ), 'type' => 'preview', ), 'max-video-preview' => array( 'label' => __( 'max-video-preview', 'noindex-seo' ), 'desc' => __( 'Maximum video preview seconds (-1 = no limit)', 'noindex-seo' ), 'type' => 'int', ), 'unavailable_after' => array( 'label' => __( 'unavailable_after', 'noindex-seo' ), 'desc' => __( 'Stop indexing this page after this date and time', 'noindex-seo' ), 'type' => 'datetime', ), ); ?>

'; esc_html_e( 'Recommended defaults applied. Review the changes below and click "Save Changes" to keep them, or uncheck anything you do not want.', 'noindex-seo' ); echo '

'; } } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag set by our own admin-post handler after a nonce check. if ( '1' === ( isset( $_GET['imported'] ) && is_string( $_GET['imported'] ) ? sanitize_key( wp_unslash( $_GET['imported'] ) ) : '' ) ) { echo '

'; esc_html_e( 'Settings imported successfully.', 'noindex-seo' ); echo '

'; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag set by our own admin-post handler after a nonce check. if ( '1' === ( isset( $_GET['import_error'] ) && is_string( $_GET['import_error'] ) ? sanitize_key( wp_unslash( $_GET['import_error'] ) ) : '' ) ) { echo '

'; esc_html_e( 'The settings file could not be imported: it is missing, too large, or not a valid noindex SEO export.', 'noindex-seo' ); echo '

'; } ?> '; foreach ( $tabs as $tab_slug => $tab_label ) { printf( '%s', esc_url( add_query_arg( 'tab', $tab_slug, $page_url ) ), $tab_slug === $current_tab ? ' nav-tab-active' : '', esc_html( $tab_label ) ); } echo ''; ?>

__( 'Enable all directives for the 15 contexts flagged as recommended.', 'noindex-seo' ), ) ); ?>

0
0

$section ) : ?>

$field ) : ?>
>
$config ) : ?>

'', 'value' => '', ), ); // One empty row for the first rule. ?>