noindex-seo/noindex-seo.php
2026-11-04 13:43:04 +00:00

6292 lines
238 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Plugin Name: noindex SEO
* Plugin URI: https://www.robotstxt.software/plugins/noindex-seo/
* Description: Control search engine indexing with robots directives (noindex, nofollow, noarchive, nosnippet, noimageindex) for specific parts of your WordPress site.
* Version: 3.7.0
* Requires at least: 7.0
* Requires PHP: 8.3
* Author: ROBOTSTXT
* Author URI: https://www.robotstxt.software/
* License: GPL-3.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-3.0.txt
* Text Domain: noindex-seo
* Domain Path: /languages
*
* @package noindex-seo
*/
defined( 'ABSPATH' ) || die( 'Bye bye!' );
/**
* Plugin version constant. Used for asset cache-busting and internal version checks.
*
* @since 2.0.1
* @since 2.0.2 Bumped to 2.0.2 for bulk-action postmeta fix and dead-context cleanup.
* @since 3.0.0 Major release: storage consolidated into a single autoloaded option
* (`noindex_seo_settings`); legacy options kept as non-autoloaded for
* rollback safety. Filterable conflict-detection list. One-click
* "Apply recommended defaults" button.
* @since 3.0.1 Self-healing migration: re-runs the v3 migration if the
* consolidated option is missing despite the version claim.
* @since 3.0.2 Added per-term granular control for taxonomies (category,
* post_tag, and public custom taxonomies like product_cat).
* @since 3.0.3 Added the "Robots" column to taxonomy list tables (mirrors
* the existing post-list Robots column) so admins can see at a
* glance which terms have an override.
* @since 3.0.4 Moved the "Apply Recommended Defaults" button from the top
* of the settings page to immediately above the Search section,
* so it stops competing with the stat cards for above-the-fold
* attention.
* @since 3.1.0 Three HIGH-priority audit items: (1) WP core XML sitemap
* integration — noindexed URLs drop out of /wp-sitemap.xml;
* (2) per-CPT global defaults — every public custom post type
* gets its own directive settings; (3) REST API exposure —
* /wp-json/noindex-seo/v1/{settings,effective} so headless
* consumers can read the configuration.
* @since 3.1.1 Security hardening on the REST endpoints: /settings now
* requires `manage_options`; /effective is public only for
* published + non-password-protected posts and requires
* `edit_post` for everything else. The previous `__return_true`
* callback would have leaked the full configuration to anyone.
* @since 3.1.2 Audit-driven maintenance release: fixed broken CVE gate in
* bin/preflight.sh, un-nested the settings page forms (HTML5
* compliance), added load_plugin_textdomain() for bundled
* translations, pinned all dev dependencies, wired up coverage
* measurement, refreshed project docs.
* @since 3.1.3 Compatibility release: PHP 5.6-8.5 and WordPress 4.0-7.1
* supported (declared floors now match reality — the pre-5.7
* <meta name="robots"> 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.
* @since 3.7.0 Bridge release: on-demand import of robots overrides from
* other SEO plugins (Yoast, Rank Math, SEOPress, AIOSEO) and
* virtual robots.txt management (bot rules appended to the
* WordPress-generated robots.txt, inactive by default).
*/
define( 'NOINDEX_SEO_VERSION', '3.7.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<int, string> 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<int, string> 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<int, string> 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<string, int|string|true> $directives Directive name => true or value.
* @return array<int, string> 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' => [ '<context>' => [ '<directive>' => 0|1|'', ... ], ... ],
* 'rules' => [ [ 'field' => '<meta key>', 'value' => '<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<string, array<string, int|string>>,
* rules: array<int, array{field: string, value: string}>,
* robots_txt: array{
* enabled: int,
* rules: array<int, array{user_agent: string, policy: string}>
* },
* 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(),
'robots_txt' => array(
'enabled' => 0,
'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'] );
}
// Virtual robots.txt management (3.7.0).
if ( isset( $saved['robots_txt'] ) && is_array( $saved['robots_txt'] ) ) {
$defaults['robots_txt']['enabled'] = empty( $saved['robots_txt']['enabled'] ) ? 0 : 1;
if ( isset( $saved['robots_txt']['rules'] ) ) {
$defaults['robots_txt']['rules'] = noindex_seo_sanitize_robots_txt_rules( $saved['robots_txt']['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<int, array{field: string, value: string}> 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;
}
/**
* Sanitizes the virtual robots.txt bot rules (3.7.0).
*
* Each rule is a `user_agent` string (letters, digits, `-`, `_`, `.`, `/`,
* `*` — the characters valid in a robots.txt User-agent token) plus a policy
* of `block` (Disallow: /) or `allow` (Allow: /). Empty agents are dropped,
* duplicates collapse (first policy wins) and at most 30 rules are kept.
*
* @since 3.7.0
*
* @param mixed $raw Untrusted rules array.
* @return array<int, array{user_agent: string, policy: string}> Sanitized rules.
*/
function noindex_seo_sanitize_robots_txt_rules( $raw ) {
if ( ! is_array( $raw ) ) {
return array();
}
$rules = array();
$seen = array();
foreach ( $raw as $rule ) {
if ( ! is_array( $rule ) || ! isset( $rule['user_agent'], $rule['policy'] ) ) {
continue;
}
$agent = is_scalar( $rule['user_agent'] ) ? preg_replace( '/[^A-Za-z0-9_*.\-\/]/', '', (string) $rule['user_agent'] ) : '';
$agent = trim( substr( (string) $agent, 0, 100 ), " \t\0\x0B-_." ); // Length-capped; a lone '*' (all crawlers) stays valid.
if ( '' === $agent || isset( $seen[ strtolower( $agent ) ] ) ) {
continue;
}
$policy = ( 'allow' === $rule['policy'] ) ? 'allow' : 'block';
$seen[ strtolower( $agent ) ] = true;
$rules[] = array(
'user_agent' => $agent,
'policy' => $policy,
);
if ( count( $rules ) >= 30 ) {
break;
}
}
return $rules;
}
/**
* Returns the well-known AI crawler User-agent tokens for the preset button.
*
* Source: public crawler documentation of the main AI vendors (OpenAI,
* Anthropic, Google, Perplexity, Amazon, Meta, Apple, Common Crawl, Cohere,
* ByteDance). Filterable so the list can track new crawlers without a release.
*
* @since 3.7.0
*
* @return array<int, string> User-agent tokens.
*/
function noindex_seo_get_ai_bots() {
/**
* Filter the AI crawler User-agent tokens offered by the preset button.
*
* @since 3.7.0
*
* @param array<int, string> $bots User-agent tokens.
*/
return apply_filters(
'noindex_seo_ai_bots',
array(
'GPTBot',
'ChatGPT-User',
'OAI-SearchBot',
'ClaudeBot',
'Claude-User',
'anthropic-ai',
'Google-Extended',
'PerplexityBot',
'Amazonbot',
'meta-externalagent',
'Applebot-Extended',
'CCBot',
'cohere-ai',
'Bytespider',
'YouBot',
)
);
}
/**
* Returns the well-known search engine crawler User-agent tokens.
*
* @since 3.7.0
*
* @return array<int, string> User-agent tokens.
*/
function noindex_seo_get_search_bots() {
/**
* Filter the search engine crawler User-agent tokens offered by the preset button.
*
* @since 3.7.0
*
* @param array<int, string> $bots User-agent tokens.
*/
return apply_filters(
'noindex_seo_search_bots',
array(
'Googlebot',
'Bingbot',
'DuckDuckBot',
'Slurp',
'Baiduspider',
'YandexBot',
)
);
}
/**
* Returns the robots.txt block the plugin appends, or '' when inactive.
*
* Each rule renders as its own `User-agent: <token>` group:
*
* User-agent: GPTBot
* Disallow: /
*
* `allow` rules render `Allow: /` so they can override a broader block
* (the last matching group wins in most crawlers' implementations).
*
* @since 3.7.0
*
* @return string Robots.txt snippet (no trailing newline), '' when disabled or empty.
*/
function noindex_seo_get_robots_txt_block() {
$settings = noindex_seo_get_settings();
if ( empty( $settings['robots_txt']['enabled'] ) ) {
return '';
}
$lines = array();
foreach ( $settings['robots_txt']['rules'] as $rule ) {
$lines[] = 'User-agent: ' . $rule['user_agent'];
$lines[] = ( 'allow' === $rule['policy'] ) ? 'Allow: /' : 'Disallow: /';
$lines[] = '';
}
return trim( implode( "\n", $lines ) );
}
/**
* Extends the virtual robots.txt generated by WordPress with the configured
* bot rules (3.7.0).
*
* Inactive by default; only appends when the feature is enabled and rules
* exist. This extends — never replaces — the core output, and only applies
* when WordPress serves robots.txt virtually (no physical robots.txt file
* in the site root and "Search engines visibility" allowed).
*
* Hooked to the {@see 'robots_txt'} filter.
*
* @since 3.7.0
*
* @param string $output Robots.txt output so far.
* @return string Filtered output.
*/
function noindex_seo_filter_robots_txt( $output ) {
$block = noindex_seo_get_robots_txt_block();
if ( '' === $block ) {
return $output;
}
return $output . "\n\n" . $block;
}
add_filter( 'robots_txt', 'noindex_seo_filter_robots_txt' );
/**
* Returns the supported import sources: other SEO plugins whose robots
* directive data noindex SEO can import (3.7.0, spec section 5).
*
* Each source declares how to read its per-post (and, where stored, per-term)
* noindex / nofollow flags:
*
* - `is` => exact meta value match (e.g. Yoast stores '1').
* - `has` => the value contains the token (Rank Math stores a serialized
* array of directive names).
*
* Sources are data-driven so third parties can register or correct one via
* the filter. Only the two directives every source shares (noindex,
* nofollow) are imported; anything richer stays for the importing plugin's
* own UI.
*
* @since 3.7.0
*
* @return array<string, array{
* label: string,
* posts: array{noindex: array{key: string, is?: string, has?: string}, nofollow: array{key: string, is?: string, has?: string}},
* terms?: array{noindex: array{key: string, is?: string, has?: string}, nofollow: array{key: string, is?: string, has?: string}}
* }> Source registry.
*/
function noindex_seo_get_import_sources() {
$sources = array(
'yoast' => array(
'label' => 'Yoast SEO',
'posts' => array(
'noindex' => array(
'key' => '_yoast_wpseo_meta-robots-noindex',
'is' => '1',
),
'nofollow' => array(
'key' => '_yoast_wpseo_meta-robots-nofollow',
'is' => '1',
),
),
'terms' => array(
'noindex' => array(
'key' => '_yoast_wpseo_meta-robots-noindex',
'is' => '1',
),
'nofollow' => array(
'key' => '_yoast_wpseo_meta-robots-nofollow',
'is' => '1',
),
),
),
'rankmath' => array(
'label' => 'Rank Math SEO',
'posts' => array(
'noindex' => array(
'key' => 'rank_math_robots',
'has' => 'noindex',
),
'nofollow' => array(
'key' => 'rank_math_robots',
'has' => 'nofollow',
),
),
'terms' => array(
'noindex' => array(
'key' => 'rank_math_robots',
'has' => 'noindex',
),
'nofollow' => array(
'key' => 'rank_math_robots',
'has' => 'nofollow',
),
),
),
'seopress' => array(
'label' => 'SEOPress',
'posts' => array(
'noindex' => array(
'key' => '_seopress_robots_index',
'is' => 'no',
),
'nofollow' => array(
'key' => '_seopress_robots_follow',
'is' => 'no',
),
),
),
'aioseo' => array(
'label' => 'All in One SEO',
'posts' => array(
'noindex' => array(
'key' => '_aioseop_noindex',
'is' => 'on',
),
'nofollow' => array(
'key' => '_aioseop_nofollow',
'is' => 'on',
),
),
),
);
/**
* Filter the importable SEO plugin sources.
*
* @since 3.7.0
*
* @param array $sources Source registry (see noindex_seo_get_import_sources()).
*/
return apply_filters( 'noindex_seo_import_sources', $sources );
}
/**
* Builds the meta_query clause that finds content flagged by a source.
*
* @since 3.7.0
*
* @param array<string, array<string, mixed>> $flags noindex / nofollow flag specs of one source.
* @return array<int, array<string, mixed>> meta_query clauses (unkeyed; caller wraps with OR).
*/
function noindex_seo_import_flags_meta_query( array $flags ) {
$clauses = array();
foreach ( $flags as $spec ) {
if ( isset( $spec['is'] ) ) {
$clauses[] = array(
'key' => $spec['key'],
'value' => $spec['is'],
'compare' => '=',
);
} elseif ( isset( $spec['has'] ) ) {
$clauses[] = array(
'key' => $spec['key'],
'value' => $spec['has'],
'compare' => 'LIKE',
);
}
}
return $clauses;
}
/**
* Returns the shared post-type and status coverage for finding posts flagged
* by a source.
*
* Attachments (status `inherit`) and CPTs that hide from search must be
* included: 'post_type' => 'any' would silently exclude both, and SEO
* plugins do store flags on media.
*
* @since 3.7.0
*
* @return array{post_types: array<int, string>, post_statuses: array<int, string>} Coverage lists.
*/
function noindex_seo_import_posts_coverage() {
return array(
'post_types' => array_values( get_post_types( array( 'show_ui' => true ), 'names' ) ),
'post_statuses' => array( 'publish', 'draft', 'pending', 'private', 'future', 'inherit' ),
);
}
/**
* Counts the importable posts and terms per source.
*
* Detection is data-driven, not activation-driven: leftover meta from an
* uninstalled SEO plugin still counts (that is exactly the migration case).
* The counts are cached in a 15-minute transient because the LIKE-based
* meta scans are not free on large sites; noindex_seo_run_import()
* invalidates the cache after an import.
*
* @since 3.7.0
*
* @return array<string, array{label: string, posts: int, terms: int}> Counts per source slug.
*/
function noindex_seo_count_import_sources() {
$cached = get_transient( 'noindex_seo_import_counts' );
if ( is_array( $cached ) ) {
// Transients can hold stale or foreign shapes: validate per row.
$valid = array();
foreach ( $cached as $slug => $row ) {
if ( is_string( $slug ) && is_array( $row ) && isset( $row['label'], $row['posts'], $row['terms'] ) ) {
$valid[ $slug ] = array(
'label' => (string) $row['label'],
'posts' => (int) $row['posts'],
'terms' => (int) $row['terms'],
);
}
}
if ( array() !== $valid ) {
return $valid;
}
}
$counts = array();
$coverage = noindex_seo_import_posts_coverage();
foreach ( noindex_seo_get_import_sources() as $slug => $source ) {
$found = get_posts(
array(
'post_type' => $coverage['post_types'],
'post_status' => $coverage['post_statuses'],
'fields' => 'ids',
'posts_per_page' => -1,
'no_found_rows' => true,
'suppress_filters' => true,
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
array_merge( array( 'relation' => 'OR' ), noindex_seo_import_flags_meta_query( $source['posts'] ) ),
),
)
);
$term_count = 0;
if ( isset( $source['terms'] ) ) {
$terms = get_terms(
array(
'taxonomy' => get_taxonomies( array( 'public' => true ), 'names' ),
'hide_empty' => false,
'fields' => 'ids',
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
array_merge( array( 'relation' => 'OR' ), noindex_seo_import_flags_meta_query( $source['terms'] ) ),
),
)
);
$term_count = is_array( $terms ) ? count( $terms ) : 0;
}
$counts[ $slug ] = array(
'label' => $source['label'],
'posts' => count( $found ),
'terms' => $term_count,
);
}
set_transient( 'noindex_seo_import_counts', $counts, 15 * MINUTE_IN_SECONDS );
return $counts;
}
/**
* Reads one flag of a source from a raw meta value.
*
* @since 3.7.0
*
* @param mixed $meta_value Raw meta value.
* @param array<string,mixed> $spec Flag spec (key + is|has).
* @return bool True when the source flag is on.
*/
function noindex_seo_source_flag_is_on( $meta_value, array $spec ) {
if ( isset( $spec['is'] ) ) {
return is_scalar( $meta_value ) && (string) $meta_value === $spec['is'];
}
if ( isset( $spec['has'] ) && is_scalar( $spec['has'] ) ) {
$token = (string) $spec['has'];
if ( is_string( $meta_value ) ) {
return false !== strpos( $meta_value, $token );
}
if ( is_array( $meta_value ) ) {
return in_array( $token, $meta_value, true );
}
}
return false;
}
/**
* Imports the robots overrides of the given sources (3.7.0, spec section 5).
*
* Rules, per the specification:
*
* - On-demand: only runs when the user asked for it.
* - Never overwrites: content that already carries a `_noindex_seo_override`
* meta row (even an "off" one) is skipped and counted.
* - Only the shared noindex / nofollow booleans are imported; they become
* granular per-post / per-term overrides with the override flag set.
*
* @since 3.7.0
*
* @param array<int, string> $slugs Source slugs to import.
* @return array{posts: int, terms: int, skipped_posts: int, skipped_terms: int} Totals across sources.
*/
function noindex_seo_run_import( array $slugs ) {
$totals = array(
'posts' => 0,
'terms' => 0,
'skipped_posts' => 0,
'skipped_terms' => 0,
);
$sources = noindex_seo_get_import_sources();
foreach ( $slugs as $slug ) {
if ( ! isset( $sources[ $slug ] ) ) {
continue;
}
$source = $sources[ $slug ];
// Posts.
$coverage = noindex_seo_import_posts_coverage();
$post_ids = get_posts(
array(
'post_type' => $coverage['post_types'],
'post_status' => $coverage['post_statuses'],
'fields' => 'ids',
'posts_per_page' => -1,
'no_found_rows' => true,
'suppress_filters' => true,
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
array_merge( array( 'relation' => 'OR' ), noindex_seo_import_flags_meta_query( $source['posts'] ) ),
),
)
);
foreach ( (array) $post_ids as $post_id ) {
$post_id = (int) $post_id;
// Never overwrite existing data (an explicit "off" row counts as data too).
if ( metadata_exists( 'post', $post_id, '_noindex_seo_override' ) ) {
++$totals['skipped_posts'];
continue;
}
$noindex = noindex_seo_source_flag_is_on( get_post_meta( $post_id, $source['posts']['noindex']['key'], true ), $source['posts']['noindex'] );
$nofollow = noindex_seo_source_flag_is_on( get_post_meta( $post_id, $source['posts']['nofollow']['key'], true ), $source['posts']['nofollow'] );
if ( ! $noindex && ! $nofollow ) {
continue; // False positive of the LIKE query: nothing to import.
}
update_post_meta( $post_id, '_noindex_seo_override', 1 );
update_post_meta( $post_id, '_noindex_seo_noindex', $noindex ? 1 : 0 );
update_post_meta( $post_id, '_noindex_seo_nofollow', $nofollow ? 1 : 0 );
++$totals['posts'];
}
// Terms (only sources that store term meta).
if ( isset( $source['terms'] ) ) {
$term_ids = get_terms(
array(
'taxonomy' => get_taxonomies( array( 'public' => true ), 'names' ),
'hide_empty' => false,
'fields' => 'ids',
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
array_merge( array( 'relation' => 'OR' ), noindex_seo_import_flags_meta_query( $source['terms'] ) ),
),
)
);
foreach ( is_array( $term_ids ) ? $term_ids : array() as $term_id ) {
if ( metadata_exists( 'term', $term_id, '_noindex_seo_override' ) ) {
++$totals['skipped_terms'];
continue;
}
$noindex = noindex_seo_source_flag_is_on( get_term_meta( $term_id, $source['terms']['noindex']['key'], true ), $source['terms']['noindex'] );
$nofollow = noindex_seo_source_flag_is_on( get_term_meta( $term_id, $source['terms']['nofollow']['key'], true ), $source['terms']['nofollow'] );
if ( ! $noindex && ! $nofollow ) {
continue;
}
update_term_meta( $term_id, '_noindex_seo_override', 1 );
update_term_meta( $term_id, '_noindex_seo_noindex', $noindex ? 1 : 0 );
update_term_meta( $term_id, '_noindex_seo_nofollow', $nofollow ? 1 : 0 );
++$totals['terms'];
}
}
}
// The counts shown on the Tools tab describe pre-import state: drop them.
delete_transient( 'noindex_seo_import_counts' );
return $totals;
}
/**
* 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<string, int|string|true> 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<string, int|string|true> 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<string, mixed> $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 <meta name="robots"> 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<int|string, int|string|true> $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 <meta name="robots"> tag on wp_head.
add_action(
'wp_head',
function () use ( $tokens ) {
echo '<meta name="robots" content="' . esc_attr( implode( ', ', $tokens ) ) . '">' . "\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<string, string> $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<string,string> 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<string, mixed> $args WP_Query arguments for the sitemap post query.
* @param string $post_type Post type being listed.
* @return array<string, mixed> 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<string, mixed> $args WP_Term_Query arguments for the sitemap term query.
* @param string $taxonomy Taxonomy being listed.
* @return array<string, mixed> 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<string, mixed> $args WP_User_Query arguments for the sitemap user query.
* @return array<string, mixed> 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 `<meta name="robots">` 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 `<meta name="robots">` 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, rules,
* robots_txt, 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<string, string> Directive slug => SVG markup.
*/
function noindex_seo_get_directive_svg_icons() {
$badge = '<circle cx="17.5" cy="17.5" r="4"/><path d="M15.7 17.5h3.6"/>';
$open = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">';
$close = '</svg>';
return array(
'noindex' => $open . '<circle cx="8" cy="8" r="5"/><path d="M11.8 11.8 14 14"/>' . $badge . $close,
'nofollow' => $open . '<rect x="3" y="6" width="9" height="6" rx="3" transform="rotate(-45 7.5 9)"/>' . $badge . $close,
'noarchive' => $open . '<path d="M3.5 5.5h10v9h-10z"/><path d="M3.5 8.5h10"/>' . $badge . $close,
'nosnippet' => $open . '<path d="M5 3.5h5.5l3 3V14H5z"/><path d="M10.5 3.5v3h3"/>' . $badge . $close,
'noimageindex' => $open . '<rect x="3" y="4.5" width="10.5" height="9.5" rx="1"/><circle cx="6.8" cy="7.8" r="1.3"/><path d="M4.8 13l3-3 2 2 1.6-1.6 1.6 1.6"/>' . $badge . $close,
'notranslate' => $open . '<circle cx="8" cy="8" r="5.5"/><path d="M2.5 8h11"/><path d="M8 2.5c-1.6 1.5-2.5 3.5-2.5 5.5s.9 4 2.5 5.5c1.6-1.5 2.5-3.5 2.5-5.5s-.9-4-2.5-5.5z"/>' . $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 ] )
? '<span aria-hidden="true">' . esc_html( $emoji[ $directive ] ) . '</span>'
: '';
}
/**
* 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 and the robots.txt preset bot lists..
wp_localize_script(
'noindex-seo-admin',
'noindexSeoAdmin',
array(
'successMessage' => __( 'Settings saved successfully!', 'noindex-seo' ),
'expandAll' => __( 'Expand All', 'noindex-seo' ),
'collapseAll' => __( 'Collapse All', 'noindex-seo' ),
'aiBots' => array_values( noindex_seo_get_ai_bots() ),
'searchBots' => array_values( noindex_seo_get_search_bots() ),
)
);
}
/**
* 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<string|int, string> $links Array of existing action links for the plugin.
* @return array<string|int, string> Modified array including the "Settings" link.
*/
function noindex_seo_settings_link( array $links ) {
$settings_link = '<a href="' . esc_url( admin_url( 'options-general.php?page=noindex_seo' ) ) . '">' . esc_html__( 'Settings', 'noindex-seo' ) . '</a>';
$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<string, string> 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<int, string> 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 '<div class="notice notice-warning is-dismissible"><p>';
// 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 '</p></div>';
}
);
$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 '<div class="notice notice-warning is-dismissible"><p>';
// 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 '</p></div>';
}
);
}
}
}
}
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', 'robotstxt' ), 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
} elseif ( 'robotstxt' === $scope ) {
// Virtual robots.txt management (3.7.0): feature toggle + bot rules
// from the parallel agent/policy arrays of the Robots.txt tab.
// phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified above.
$settings['robots_txt']['enabled'] = isset( $_POST['noindex_seo_robotstxt_enabled'] ) ? 1 : 0;
$raw_rules = array();
if ( isset( $_POST['noindex_seo_robotstxt_agent'], $_POST['noindex_seo_robotstxt_policy'] )
&& is_array( $_POST['noindex_seo_robotstxt_agent'] ) && is_array( $_POST['noindex_seo_robotstxt_policy'] ) ) {
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- array input; every element is sanitized in the loop below.
$agents = (array) wp_unslash( $_POST['noindex_seo_robotstxt_agent'] );
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- array input; every element is sanitized in the loop below.
$policies = (array) wp_unslash( $_POST['noindex_seo_robotstxt_policy'] );
foreach ( $policies as $index => $policy ) {
$raw_rules[] = array(
'user_agent' => isset( $agents[ $index ] ) && is_scalar( $agents[ $index ] ) ? sanitize_text_field( wp_unslash( (string) $agents[ $index ] ) ) : '',
'policy' => is_scalar( $policy ) ? sanitize_key( wp_unslash( (string) $policy ) ) : '',
);
}
}
$settings['robots_txt']['rules'] = noindex_seo_sanitize_robots_txt_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<string, mixed> 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<string, array<string, int|string>>,
* rules: array<int, array{field: string, value: string}>,
* 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'] );
}
// Virtual robots.txt rules (3.7.0) ride the JSON backup as well.
if ( isset( $raw['robots_txt'] ) && is_array( $raw['robots_txt'] ) ) {
$settings['robots_txt']['enabled'] = empty( $raw['robots_txt']['enabled'] ) ? 0 : 1;
if ( isset( $raw['robots_txt']['rules'] ) ) {
$settings['robots_txt']['rules'] = noindex_seo_sanitize_robots_txt_rules( $raw['robots_txt']['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' );
/**
* Handles the "Import from other plugins" action (3.7.0, spec section 5).
*
* On-demand and confirmed by the user: only the sources checked in the form
* are imported, and noindex SEO never overwrites content that already
* carries its own override data (skipped and counted instead). Redirects
* back to the tools tab with the totals for the result notices.
*
* Hooked to the {@see 'admin_post_noindex_seo_plugin_import'} action.
*
* @since 3.7.0
*
* @return void
*/
function noindex_seo_handle_plugin_import() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'Permission denied.', 'noindex-seo' ) );
}
check_admin_referer( 'noindex_seo_plugin_import' );
$known = array_keys( noindex_seo_get_import_sources() );
$slugs = array();
$raw_selection = isset( $_POST['noindex_seo_import_sources'] ) && is_array( $_POST['noindex_seo_import_sources'] )
? wp_unslash( $_POST['noindex_seo_import_sources'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- array of slugs, whitelisted against the known sources below.
: array();
foreach ( $raw_selection as $slug ) {
if ( is_string( $slug ) && in_array( sanitize_key( $slug ), $known, true ) ) {
$slugs[] = sanitize_key( $slug );
}
}
$redirect = admin_url( 'options-general.php?page=noindex_seo&tab=tools' );
if ( array() === $slugs ) {
wp_safe_redirect( add_query_arg( 'plugin_import_empty', '1', $redirect ) );
exit;
}
$totals = noindex_seo_run_import( $slugs );
wp_safe_redirect(
add_query_arg(
array(
'plugin_import_posts' => $totals['posts'],
'plugin_import_terms' => $totals['terms'],
'plugin_import_skipped_posts' => $totals['skipped_posts'],
'plugin_import_skipped_terms' => $totals['skipped_terms'],
),
( $totals['posts'] || $totals['terms'] || $totals['skipped_posts'] || $totals['skipped_terms'] )
? $redirect
: add_query_arg( 'plugin_import_done', '1', $redirect )
)
);
exit;
}
add_action( 'admin_post_noindex_seo_plugin_import', 'noindex_seo_handle_plugin_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<int, array{context: string, directive: string, status: string}> 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=<context>]
* : Only list the given context slug.
*
* [--format=<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<int, string> $args Positional arguments (unused).
* @param array<string, mixed> $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>
* : Context slug (see `wp noindex-seo list`).
*
* [<directive>...]
* : 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<int, string> $args [context, directive...].
* @param array<string, mixed> $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 <context> [<directive>...]' );
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>
* : Context slug (see `wp noindex-seo list`).
*
* [<directive>...]
* : 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<int, string> $args [context, directive...].
* @param array<string, mixed> $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 <context> [<directive>...]' );
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
*
* [<file>]
* : 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<int, string> $args [<file>].
* @param array<string, mixed> $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
*
* <file>
* : 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<int, string> $args [<file>].
* @param array<string, mixed> $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 <file> [--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
*
* <post_id>...
* : 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<int, string> $args Post IDs.
* @param array<string, mixed> $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 <post_id>... [--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.
* @since 3.7.1 Adds 'custom-fields' post type support for the registered
* types: without it the REST API exposes no `meta` field and
* the block editor sidebar silently drops every save on
* custom post types registered without that support.
*
* @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' );
// The REST API (and with it the block editor sidebar) only exposes the
// `meta` field for post types that support 'custom-fields'. Custom post
// types registered without it (a very common registration) would
// silently drop every sidebar save with an HTTP 200, so the support is
// added for exactly the post types the plugin registers meta on.
foreach ( $post_types as $post_type ) {
if ( ! post_type_supports( $post_type, 'custom-fields' ) ) {
add_post_type_support( $post_type, 'custom-fields' );
}
}
// 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;
}
?>
<div class="noindex-seo-meta-box">
<p class="noindex-seo-meta-override">
<label>
<input type="checkbox" name="noindex_seo_override" value="1" <?php checked( 1, $override ); ?> id="noindex-seo-override-toggle">
<strong><?php esc_html_e( 'Override global settings', 'noindex-seo' ); ?></strong>
</label>
</p>
<p class="description noindex-seo-meta-note">
<?php esc_html_e( 'When enabled, these directives will override the global settings for this specific content.', 'noindex-seo' ); ?>
</p>
<div id="noindex-seo-directives-container" class="noindex-seo-directives-box<?php echo $override ? '' : ' hidden'; ?>">
<div class="noindex-seo-directive-list">
<label class="noindex-seo-directive-row">
<input type="checkbox" name="noindex_seo_noindex" value="1" <?php checked( 1, $noindex ); ?>>
<span><strong><?php echo noindex_seo_get_directive_icon_html( 'noindex' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?> noindex</strong> — <?php esc_html_e( 'Prevent indexing', 'noindex-seo' ); ?></span>
</label>
<label class="noindex-seo-directive-row">
<input type="checkbox" name="noindex_seo_nofollow" value="1" <?php checked( 1, $nofollow ); ?>>
<span><strong><?php echo noindex_seo_get_directive_icon_html( 'nofollow' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?> nofollow</strong> — <?php esc_html_e( 'Prevent link following', 'noindex-seo' ); ?></span>
</label>
<label class="noindex-seo-directive-row">
<input type="checkbox" name="noindex_seo_noarchive" value="1" <?php checked( 1, $noarchive ); ?>>
<span><strong><?php echo noindex_seo_get_directive_icon_html( 'noarchive' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?> noarchive</strong> — <?php esc_html_e( 'Prevent caching', 'noindex-seo' ); ?></span>
</label>
<label class="noindex-seo-directive-row">
<input type="checkbox" name="noindex_seo_nosnippet" value="1" <?php checked( 1, $nosnippet ); ?>>
<span><strong><?php echo noindex_seo_get_directive_icon_html( 'nosnippet' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?> nosnippet</strong> — <?php esc_html_e( 'Prevent snippets', 'noindex-seo' ); ?></span>
</label>
<label class="noindex-seo-directive-row">
<input type="checkbox" name="noindex_seo_noimageindex" value="1" <?php checked( 1, $noimageindex ); ?>>
<span><strong><?php echo noindex_seo_get_directive_icon_html( 'noimageindex' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?> noimageindex</strong> — <?php esc_html_e( 'Prevent image indexing', 'noindex-seo' ); ?></span>
</label>
<label class="noindex-seo-directive-row">
<input type="checkbox" name="noindex_seo_notranslate" value="1" <?php checked( 1, $notranslate ); ?>>
<span><strong><?php echo noindex_seo_get_directive_icon_html( 'notranslate' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?> notranslate</strong> — <?php esc_html_e( 'Prevent translation', 'noindex-seo' ); ?></span>
</label>
</div>
<div class="noindex-seo-value-list">
<p class="noindex-seo-values-title"><?php esc_html_e( 'Value directives (empty = off):', 'noindex-seo' ); ?></p>
<label class="noindex-seo-directive-row noindex-seo-value-row">
<input type="number" min="-1" step="1" placeholder="<?php esc_attr_e( 'Off', 'noindex-seo' ); ?>" name="noindex_seo_max-snippet" value="<?php echo esc_attr( (string) $max_snippet ); ?>">
<span><strong>max-snippet</strong> — <?php esc_html_e( 'Maximum snippet length in characters (-1 = no limit)', 'noindex-seo' ); ?></span>
</label>
<label class="noindex-seo-directive-row noindex-seo-value-row">
<select name="noindex_seo_max-image-preview">
<option value="" <?php selected( '', $max_image_preview ); ?>><?php esc_html_e( 'Off', 'noindex-seo' ); ?></option>
<option value="none" <?php selected( 'none', $max_image_preview ); ?>><?php esc_html_e( 'none', 'noindex-seo' ); ?></option>
<option value="standard" <?php selected( 'standard', $max_image_preview ); ?>><?php esc_html_e( 'standard', 'noindex-seo' ); ?></option>
<option value="large" <?php selected( 'large', $max_image_preview ); ?>><?php esc_html_e( 'large', 'noindex-seo' ); ?></option>
</select>
<span><strong>max-image-preview</strong> — <?php esc_html_e( 'Maximum image preview size', 'noindex-seo' ); ?></span>
</label>
<label class="noindex-seo-directive-row noindex-seo-value-row">
<input type="number" min="-1" step="1" placeholder="<?php esc_attr_e( 'Off', 'noindex-seo' ); ?>" name="noindex_seo_max-video-preview" value="<?php echo esc_attr( (string) $max_video_preview ); ?>">
<span><strong>max-video-preview</strong> — <?php esc_html_e( 'Maximum video preview seconds (-1 = no limit)', 'noindex-seo' ); ?></span>
</label>
<label class="noindex-seo-directive-row noindex-seo-value-row">
<input type="datetime-local" name="noindex_seo_unavailable_after" value="<?php echo esc_attr( str_replace( ' ', 'T', (string) $unavailable_after ) ); ?>">
<span><strong>unavailable_after</strong> — <?php esc_html_e( 'Stop indexing after this date and time', 'noindex-seo' ); ?></span>
</label>
</div>
</div>
<!-- Information Section -->
<div class="noindex-seo-reference">
<p class="noindex-seo-reference-title">
<?php esc_html_e( 'Effective Directives:', 'noindex-seo' ); ?>
</p>
<?php if ( $override ) : ?>
<?php
// Show what will be applied with override (booleans + values).
$active_directives = noindex_seo_format_directives( noindex_seo_get_post_directives_map( $post->ID ) );
?>
<?php if ( ! empty( $active_directives ) ) : ?>
<p class="noindex-seo-ref noindex-seo-ref-override">
<strong><?php esc_html_e( 'Override active:', 'noindex-seo' ); ?></strong><br>
<code><?php echo esc_html( implode( ', ', $active_directives ) ); ?></code>
</p>
<?php else : ?>
<p class="noindex-seo-ref noindex-seo-ref-none">
<?php esc_html_e( 'Override enabled but no directives selected', 'noindex-seo' ); ?>
</p>
<?php endif; ?>
<?php else : ?>
<?php if ( ! empty( $global_directives ) ) : ?>
<p class="noindex-seo-ref noindex-seo-ref-global">
<strong><?php esc_html_e( 'Global settings:', 'noindex-seo' ); ?></strong><br>
<code><?php echo esc_html( implode( ', ', $global_directives ) ); ?></code>
</p>
<?php else : ?>
<p class="noindex-seo-ref noindex-seo-ref-ok">
<?php esc_html_e( 'No restrictions (indexable)', 'noindex-seo' ); ?>
</p>
<?php endif; ?>
<?php endif; ?>
</div>
<script type="text/javascript">
(function() {
var toggle = document.getElementById('noindex-seo-override-toggle');
var container = document.getElementById('noindex-seo-directives-container');
if (toggle && container) {
toggle.addEventListener('change', function() {
container.classList.toggle('hidden', !this.checked);
});
}
})();
</script>
</div>
<?php
}
/**
* Persist robots override and directive post meta from the current $_POST data.
*
* Shared by the meta box save path and the Quick Edit save path.
* Callers are responsible for nonce verification and capability checks
* before invoking this helper.
*
* @since 2.0.1
*
* @param int $post_id The post ID to update.
* @return void
*/
function noindex_seo_save_directives_from_post( $post_id ) {
// phpcs:disable WordPress.Security.NonceVerification.Missing
// Nonce verification and capability checks are performed by the callers:
// noindex_seo_save_post_meta() and noindex_seo_save_quick_edit().
$override = isset( $_POST['noindex_seo_override'] ) ? 1 : 0;
update_post_meta( $post_id, '_noindex_seo_override', $override );
if ( $override ) {
// Boolean directives: checkbox presence = 1.
foreach ( noindex_seo_get_boolean_directives() as $directive ) {
$value = isset( $_POST[ 'noindex_seo_' . $directive ] ) ? 1 : 0;
update_post_meta( $post_id, '_noindex_seo_' . $directive, $value );
}
// Value directives (3.6.0): raw input, normalized ('' = off).
foreach ( noindex_seo_get_value_directives() as $directive ) {
$raw = ( isset( $_POST[ 'noindex_seo_' . $directive ] ) && is_string( $_POST[ 'noindex_seo_' . $directive ] ) )
? sanitize_text_field( wp_unslash( $_POST[ 'noindex_seo_' . $directive ] ) )
: '';
$value = noindex_seo_normalize_directive_value( $directive, $raw );
update_post_meta( $post_id, '_noindex_seo_' . $directive, $value );
}
} else {
noindex_seo_clear_post_directives( $post_id );
}
// phpcs:enable WordPress.Security.NonceVerification.Missing
}
/**
* Save post meta when post is saved.
*
* Validates nonce, checks user permissions, and saves the override settings.
* Only saves meta if override is enabled.
*
* @since 2.0.0
*
* @param int $post_id The post ID being saved.
* @return void
*/
function noindex_seo_save_post_meta( $post_id ) {
// Check if granular control is enabled.
$granular_enabled = noindex_seo_get_config( 'granular', 0 );
if ( ! $granular_enabled ) {
return;
}
// Verify nonce. The is_string() ternary narrows the type from mixed to string
// so wp_unslash() returns string and sanitize_text_field() receives string.
if ( ! isset( $_POST['noindex_seo_meta_box_nonce'] ) ||
! wp_verify_nonce(
sanitize_text_field( wp_unslash( is_string( $_POST['noindex_seo_meta_box_nonce'] ) ? $_POST['noindex_seo_meta_box_nonce'] : '' ) ),
'noindex_seo_meta_box'
)
) {
return;
}
// Check if this is an autosave.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check user permissions.
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
noindex_seo_save_directives_from_post( $post_id );
}
add_action( 'save_post', 'noindex_seo_save_post_meta' );
/**
* Registers term meta for per-term granular control on every public taxonomy.
*
* Mirrors {@see noindex_seo_register_post_meta()} but for taxonomy terms.
* Active only when the 'taxonomies_granular' config flag is on, so the meta
* keys (and the REST exposure that goes with them) only exist when the
* administrator has opted in to per-term control.
*
* Public taxonomies are auto-detected via {@see get_taxonomies()}. This covers
* `category`, `post_tag`, and any custom public taxonomy registered by plugins
* or themes (e.g. WooCommerce's `product_cat` / `product_tag`).
*
* Hooked to the {@see 'init'} action.
*
* @since 3.0.2
* @since 3.1.3 Skipped on WordPress versions without register_term_meta()
* (pre-4.9.6) or term meta (pre-4.4): per-term control requires
* the termmeta table and its API.
*
* @return void
*/
function noindex_seo_register_term_meta() {
if ( ! noindex_seo_get_config( 'taxonomies_granular', 0 ) ) {
return;
}
if ( ! function_exists( 'register_term_meta' ) || ! function_exists( 'get_term_meta' ) ) {
return;
}
$taxonomies = get_taxonomies( array( 'public' => 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 ) : '';
}
?>
<tr class="form-field">
<th scope="row"><?php esc_html_e( 'Search Engine Visibility', 'noindex-seo' ); ?></th>
<td>
<label>
<input type="checkbox" name="noindex_seo_override" value="1" <?php checked( 1, $override ); ?> />
<?php esc_html_e( 'Override global settings for this term', 'noindex-seo' ); ?>
</label>
<div class="noindex-seo-term-directives<?php echo $override ? '' : ' hidden'; ?>">
<?php foreach ( noindex_seo_get_boolean_directives() as $directive ) : ?>
<label class="noindex-seo-term-directive">
<input type="checkbox" name="noindex_seo_<?php echo esc_attr( $directive ); ?>" value="1" <?php checked( 1, $values[ $directive ] ); ?> />
<?php echo esc_html( $directive ); ?>
</label>
<?php endforeach; ?>
<?php foreach ( noindex_seo_get_value_directives() as $directive ) : ?>
<label class="noindex-seo-term-directive noindex-seo-term-directive-value">
<?php if ( 'max-image-preview' === $directive ) : ?>
<select name="noindex_seo_<?php echo esc_attr( $directive ); ?>">
<option value="" <?php selected( '', (string) $values[ $directive ] ); ?>><?php esc_html_e( 'Off', 'noindex-seo' ); ?></option>
<option value="none" <?php selected( 'none', (string) $values[ $directive ] ); ?>><?php esc_html_e( 'none', 'noindex-seo' ); ?></option>
<option value="standard" <?php selected( 'standard', (string) $values[ $directive ] ); ?>><?php esc_html_e( 'standard', 'noindex-seo' ); ?></option>
<option value="large" <?php selected( 'large', (string) $values[ $directive ] ); ?>><?php esc_html_e( 'large', 'noindex-seo' ); ?></option>
</select>
<?php elseif ( 'unavailable_after' === $directive ) : ?>
<input type="datetime-local" name="noindex_seo_<?php echo esc_attr( $directive ); ?>" value="<?php echo esc_attr( str_replace( ' ', 'T', (string) $values[ $directive ] ) ); ?>" />
<?php else : ?>
<input type="number" min="-1" step="1" placeholder="<?php esc_attr_e( 'Off', 'noindex-seo' ); ?>" name="noindex_seo_<?php echo esc_attr( $directive ); ?>" value="<?php echo esc_attr( (string) $values[ $directive ] ); ?>" />
<?php endif; ?>
<?php echo esc_html( $directive ); ?>
</label>
<?php endforeach; ?>
</div>
<p class="description">
<?php esc_html_e( 'When override is enabled, the directives checked above apply to this term\'s archive page and take precedence over the global category / tag / archive settings.', 'noindex-seo' ); ?>
</p>
</td>
</tr>
<script>
// Toggle directive visibility based on override checkbox.
(function () {
var override = document.querySelector('input[name="noindex_seo_override"]');
var group = document.querySelector('.noindex-seo-term-directives');
if (!override || !group) return;
override.addEventListener('change', function () {
group.classList.toggle('hidden', !override.checked);
});
})();
</script>
<?php
}
/**
* Saves term meta for per-term granular control.
*
* Hooked to `edited_{$taxonomy}` for every public taxonomy by
* {@see noindex_seo_register_term_meta()}. Verifies the nonce, checks the
* user capability, then persists the override flag and — if override is on —
* the five directive values. When override is off, all directive meta is
* cleared so the term falls back to the global context settings.
*
* @since 3.0.2
* @since 3.1.3 No-ops on WordPress versions without term meta (pre-4.4).
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID (unused; required by the edited_{$taxonomy} hook signature).
* @return void
*/
function noindex_seo_save_term_meta( $term_id, $tt_id ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
if ( ! noindex_seo_get_config( 'taxonomies_granular', 0 ) ) {
return;
}
if ( ! function_exists( 'update_term_meta' ) || ! function_exists( 'delete_term_meta' ) ) {
return;
}
if ( ! isset( $_POST['noindex_seo_term_meta_nonce'] ) || ! is_string( $_POST['noindex_seo_term_meta_nonce'] ) ) {
return;
}
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['noindex_seo_term_meta_nonce'] ) ), 'noindex_seo_term_meta' ) ) {
return;
}
if ( ! current_user_can( 'manage_categories' ) ) {
return;
}
// phpcs:disable WordPress.Security.NonceVerification.Missing
// Nonce verified above.
$override = isset( $_POST['noindex_seo_override'] ) ? 1 : 0;
update_term_meta( $term_id, '_noindex_seo_override', $override );
$all_directives = noindex_seo_get_directives();
if ( $override ) {
foreach ( noindex_seo_get_boolean_directives() as $directive ) {
$value = isset( $_POST[ 'noindex_seo_' . $directive ] ) ? 1 : 0;
update_term_meta( $term_id, '_noindex_seo_' . $directive, $value );
}
foreach ( noindex_seo_get_value_directives() as $directive ) {
$raw = ( isset( $_POST[ 'noindex_seo_' . $directive ] ) && is_string( $_POST[ 'noindex_seo_' . $directive ] ) )
? sanitize_text_field( wp_unslash( $_POST[ 'noindex_seo_' . $directive ] ) )
: '';
$value = noindex_seo_normalize_directive_value( $directive, $raw );
update_term_meta( $term_id, '_noindex_seo_' . $directive, $value );
}
} else {
foreach ( $all_directives as $directive ) {
delete_term_meta( $term_id, '_noindex_seo_' . $directive );
}
}
// phpcs:enable WordPress.Security.NonceVerification.Missing
}
/**
* Add custom column to post/page list showing robots directives override status.
*
* Only adds column if granular control is enabled.
*
* @since 2.0.0
*
* @param array<string, string> $columns Existing columns.
* @return array<string, string> 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 '<div class="noindex-seo-override-data hidden" ';
foreach ( $directives_values as $key => $value ) {
echo 'data-' . esc_attr( $key ) . '="' . esc_attr( (string) $value ) . '" ';
}
echo '></div>';
if ( ! $override ) {
echo '<span class="noindex-seo-col-empty">—</span>';
return;
}
if ( empty( $directive_map ) ) {
echo '<span class="noindex-seo-col-empty">' . esc_html__( 'Override (none)', 'noindex-seo' ) . '</span>';
return;
}
// Display active directives as badges (booleans as names, value
// directives as name:value tokens).
$tokens = noindex_seo_format_directives( $directive_map );
echo '<div class="noindex-seo-badges">';
foreach ( $tokens as $token ) {
$badge_directive = ( false === strpos( $token, ':' ) ) ? $token : substr( $token, 0, strpos( $token, ':' ) );
echo '<span class="noindex-seo-badge-item">';
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 '</span>';
}
echo '</div>';
}
// 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<string, string> $columns Existing columns.
* @return array<string, string> 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 '<span class="noindex-seo-col-empty">—</span>';
}
$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 '<span class="noindex-seo-col-empty">' . esc_html__( 'Override (none)', 'noindex-seo' ) . '</span>';
}
$tokens = noindex_seo_format_directives( $term_map );
$out = '<div class="noindex-seo-badges">';
foreach ( $tokens as $token ) {
$badge_directive = ( false === strpos( $token, ':' ) ) ? $token : substr( $token, 0, strpos( $token, ':' ) );
$out .= '<span class="noindex-seo-badge-item">';
$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 .= '</span>';
}
$out .= '</div>';
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' );
?>
<fieldset class="inline-edit-col-right">
<div class="inline-edit-col">
<label class="inline-edit-group">
<span class="title"><?php esc_html_e( 'Robots Directives', 'noindex-seo' ); ?></span>
<div class="noindex-seo-quick-edit-list">
<label class="noindex-seo-quick-edit-label">
<input type="checkbox" name="noindex_seo_override" value="1" id="noindex-seo-quick-edit-override">
<strong><?php esc_html_e( 'Override global settings', 'noindex-seo' ); ?></strong>
</label>
<div id="noindex-seo-quick-edit-directives" class="noindex-seo-quick-edit-nested hidden">
<label class="noindex-seo-quick-edit-option">
<input type="checkbox" name="noindex_seo_noindex" value="1">
<?php echo noindex_seo_get_directive_icon_html( 'noindex' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?>
<?php esc_html_e( 'noindex', 'noindex-seo' ); ?>
</label>
<label class="noindex-seo-quick-edit-option">
<input type="checkbox" name="noindex_seo_nofollow" value="1">
<?php echo noindex_seo_get_directive_icon_html( 'nofollow' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?>
<?php esc_html_e( 'nofollow', 'noindex-seo' ); ?>
</label>
<label class="noindex-seo-quick-edit-option">
<input type="checkbox" name="noindex_seo_noarchive" value="1">
<?php echo noindex_seo_get_directive_icon_html( 'noarchive' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?>
<?php esc_html_e( 'noarchive', 'noindex-seo' ); ?>
</label>
<label class="noindex-seo-quick-edit-option">
<input type="checkbox" name="noindex_seo_nosnippet" value="1">
<?php echo noindex_seo_get_directive_icon_html( 'nosnippet' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?>
<?php esc_html_e( 'nosnippet', 'noindex-seo' ); ?>
</label>
<label class="noindex-seo-quick-edit-option">
<input type="checkbox" name="noindex_seo_noimageindex" value="1">
<?php echo noindex_seo_get_directive_icon_html( 'noimageindex' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?>
<?php esc_html_e( 'noimageindex', 'noindex-seo' ); ?>
</label>
<label class="noindex-seo-quick-edit-option">
<input type="checkbox" name="noindex_seo_notranslate" value="1">
<?php echo noindex_seo_get_directive_icon_html( 'notranslate' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?>
<?php esc_html_e( 'notranslate', 'noindex-seo' ); ?>
</label>
<label class="noindex-seo-quick-edit-option noindex-seo-quick-edit-value">
<input type="number" min="-1" step="1" placeholder="<?php esc_attr_e( 'Off', 'noindex-seo' ); ?>" name="noindex_seo_max-snippet">
<?php esc_html_e( 'max-snippet', 'noindex-seo' ); ?>
</label>
<label class="noindex-seo-quick-edit-option noindex-seo-quick-edit-value">
<select name="noindex_seo_max-image-preview">
<option value=""><?php esc_html_e( 'Off', 'noindex-seo' ); ?></option>
<option value="none"><?php esc_html_e( 'none', 'noindex-seo' ); ?></option>
<option value="standard"><?php esc_html_e( 'standard', 'noindex-seo' ); ?></option>
<option value="large"><?php esc_html_e( 'large', 'noindex-seo' ); ?></option>
</select>
<?php esc_html_e( 'max-image-preview', 'noindex-seo' ); ?>
</label>
<label class="noindex-seo-quick-edit-option noindex-seo-quick-edit-value">
<input type="number" min="-1" step="1" placeholder="<?php esc_attr_e( 'Off', 'noindex-seo' ); ?>" name="noindex_seo_max-video-preview">
<?php esc_html_e( 'max-video-preview', 'noindex-seo' ); ?>
</label>
<label class="noindex-seo-quick-edit-option noindex-seo-quick-edit-value">
<input type="datetime-local" name="noindex_seo_unavailable_after">
<?php esc_html_e( 'unavailable_after', 'noindex-seo' ); ?>
</label>
</div>
</div>
</label>
</div>
</fieldset>
<script type="text/javascript">
jQuery(document).ready(function($) {
// Toggle directives visibility when override checkbox changes
$('#noindex-seo-quick-edit-override').on('change', function() {
if ($(this).is(':checked')) {
$('#noindex-seo-quick-edit-directives').show();
} else {
$('#noindex-seo-quick-edit-directives').hide();
}
});
// Populate Quick Edit fields when "Edit" is clicked
$('#the-list').on('click', '.editinline', function() {
var post_id = $(this).closest('tr').attr('id').replace('post-', '');
var $row = $('#post-' + post_id);
var $data = $row.find('.noindex-seo-override-data');
// Get current values from the column (data attributes)
var override = $data.data('override');
var booleans = ['noindex', 'nofollow', 'noarchive', 'nosnippet', 'noimageindex', 'notranslate'];
var values = ['max-snippet', 'max-image-preview', 'max-video-preview', 'unavailable_after'];
// Set checkbox values
$('#noindex-seo-quick-edit-override').prop('checked', override == 1);
$.each(booleans, function(i, name) {
$('input[name="noindex_seo_' + name + '"]').prop('checked', $data.data(name) == 1);
});
// Set value directives (empty = off; unavailable_after uses a T separator)
$.each(values, function(i, name) {
var value = String($data.data(name) || '').replace(' ', 'T');
$('[name="noindex_seo_' + name + '"]').val(value);
});
// Show/hide directives based on override
if (override == 1) {
$('#noindex-seo-quick-edit-directives').show();
} else {
$('#noindex-seo-quick-edit-directives').hide();
}
});
});
</script>
<?php
}
add_action( 'quick_edit_custom_box', 'noindex_seo_quick_edit_fields', 10, 2 );
add_action( 'bulk_edit_custom_box', 'noindex_seo_quick_edit_fields', 10, 2 );
/**
* Save Quick Edit data for robots directives.
*
* @since 2.0.0
*
* @param int $post_id Post ID being saved.
* @return void
*/
function noindex_seo_save_quick_edit( $post_id ) {
// Check if granular control is enabled.
$granular_enabled = noindex_seo_get_config( 'granular', 0 );
if ( ! $granular_enabled ) {
return;
}
// Verify nonce. The is_string() ternary narrows the type from mixed to string
// so wp_unslash() returns string and sanitize_text_field() receives string.
if ( ! isset( $_POST['noindex_seo_quick_edit_nonce'] ) ||
! wp_verify_nonce(
sanitize_text_field( wp_unslash( is_string( $_POST['noindex_seo_quick_edit_nonce'] ) ? $_POST['noindex_seo_quick_edit_nonce'] : '' ) ),
'noindex_seo_quick_edit'
)
) {
return;
}
// Check user permissions.
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
// Check if we're in Quick Edit (not regular post save).
if ( ! isset( $_POST['_inline_edit'] ) ) {
return;
}
noindex_seo_save_directives_from_post( $post_id );
}
add_action( 'save_post', 'noindex_seo_save_quick_edit' );
/**
* Register custom bulk actions for robots directives.
*
* Adds "Enable Override" and "Disable Override" bulk actions.
*
* @since 2.0.0
*
* @param array<string, string> $bulk_actions Existing bulk actions.
* @return array<string, string> 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<int, string> $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(
'<div class="notice notice-success is-dismissible"><p>%s</p></div>',
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(
'<div class="notice notice-success is-dismissible"><p>%s</p></div>',
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'] ) ) : '';
?>
<select name="noindex_seo_filter">
<option value=""><?php esc_html_e( 'All robots settings', 'noindex-seo' ); ?></option>
<option value="with_override" <?php selected( $current_filter, 'with_override' ); ?>>
<?php esc_html_e( 'With override', 'noindex-seo' ); ?>
</option>
<option value="without_override" <?php selected( $current_filter, 'without_override' ); ?>>
<?php esc_html_e( 'Without override', 'noindex-seo' ); ?>
</option>
</select>
<?php
}
/**
* Filter posts query by robots override status.
*
* Modifies the query to show only posts with or without override
* based on the selected filter.
*
* @since 2.0.0
*
* @param WP_Query $query Current query object.
* @return void
*/
function noindex_seo_filter_posts_by_override( WP_Query $query ) {
// Only in admin list view.
if ( ! is_admin() || ! $query->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', 'robotstxt' ), true ) ) {
$current_tab = 'general';
}
$tabs = array(
'general' => __( 'General', 'noindex-seo' ),
'settings' => __( 'SEO Settings', 'noindex-seo' ),
'tools' => __( 'Import / Export', 'noindex-seo' ),
'robotstxt' => __( 'Robots.txt', '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',
),
);
?>
<div class="wrap noindex-seo-admin-wrap">
<h1><?php esc_html_e( 'noindex SEO Settings', 'noindex-seo' ); ?></h1>
<p><?php esc_html_e( 'Control how search engines index and display your WordPress content using robots directives.', 'noindex-seo' ); ?></p>
<?php
// Success notices for one-click actions. The form handlers redirect back
// to this page with a query flag so the notice survives the redirect.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL parameter set by our own admin-post handler after a nonce check, not user form data.
if ( isset( $_GET['suggestions_applied'] ) && is_string( $_GET['suggestions_applied'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag set by our own admin-post handler after a nonce check.
$suggestions_applied = sanitize_key( wp_unslash( $_GET['suggestions_applied'] ) );
if ( '1' === $suggestions_applied ) {
echo '<div class="notice notice-success is-dismissible"><p>';
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 '</p></div>';
}
}
// 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 '<div class="notice notice-success is-dismissible"><p>';
esc_html_e( 'Settings imported successfully.', 'noindex-seo' );
echo '</p></div>';
}
// 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 '<div class="notice notice-error is-dismissible"><p>';
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 '</p></div>';
}
?>
<?php
// Native WordPress tab navigation (core nav-tab classes, URL-based).
$page_url = admin_url( 'options-general.php?page=noindex_seo' );
echo '<nav class="nav-tab-wrapper" aria-label="' . esc_attr__( 'Settings sections', 'noindex-seo' ) . '">';
foreach ( $tabs as $tab_slug => $tab_label ) {
printf(
'<a href="%s" class="nav-tab%s">%s</a>',
esc_url( add_query_arg( 'tab', $tab_slug, $page_url ) ),
$tab_slug === $current_tab ? ' nav-tab-active' : '',
esc_html( $tab_label )
);
}
echo '</nav>';
?>
<?php if ( 'general' === $current_tab ) : ?>
<!-- General tab: implementation method and configuration options.
Own instance of the main form (scoped to this tab) so saving
from here never touches the directive grid of the SEO Settings
tab, and vice versa. -->
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
<input type="hidden" name="action" value="update_noindex_seo">
<input type="hidden" name="noindex_seo_form_scope" value="general">
<?php wp_nonce_field( 'update_noindex_seo_nonce' ); ?>
<!-- General Configuration -->
<div class="noindex-seo-general-config">
<h2>
<span class="dashicons dashicons-admin-settings"></span>
<?php esc_html_e( 'General Configuration', 'noindex-seo' ); ?>
</h2>
<div class="noindex-seo-config-option">
<label class="noindex-seo-switch">
<input
type="checkbox"
id="noindex_seo_config_seoplugins"
name="noindex_seo_config_seoplugins"
value="1"
<?php checked( 1, $option_config_seoplugins ); ?>
>
<span class="noindex-seo-slider"></span>
</label>
<label for="noindex_seo_config_seoplugins">
<?php esc_html_e( 'Disable compatibility warnings with other SEO plugins', 'noindex-seo' ); ?>
</label>
</div>
<div class="noindex-seo-config-option">
<div class="noindex-seo-config-body">
<label for="noindex_seo_config_method" class="noindex-seo-config-label">
<?php esc_html_e( 'Implementation Method', 'noindex-seo' ); ?>
</label>
<select
id="noindex_seo_config_method"
name="noindex_seo_config_method"
class="noindex-seo-config-select"
>
<option value="meta" <?php selected( $option_config_method, 'meta' ); ?>>
<?php esc_html_e( 'HTML Meta Tags (default, easier to verify)', 'noindex-seo' ); ?>
</option>
<option value="header" <?php selected( $option_config_method, 'header' ); ?>>
<?php esc_html_e( 'HTTP Headers (more robust, works with PDFs/images)', 'noindex-seo' ); ?>
</option>
<option value="both" <?php selected( $option_config_method, 'both' ); ?>>
<?php esc_html_e( 'Both (maximum compatibility)', 'noindex-seo' ); ?>
</option>
</select>
<p class="description">
<?php esc_html_e( 'Choose how noindex directives are sent to search engines. Meta tags work for HTML pages. HTTP headers work for all content types including PDFs, images, and feeds.', 'noindex-seo' ); ?>
</p>
</div>
</div>
<div class="noindex-seo-config-option">
<label class="noindex-seo-switch">
<input
type="checkbox"
id="noindex_seo_config_granular"
name="noindex_seo_config_granular"
value="1"
<?php checked( 1, $option_config_granular ); ?>
>
<span class="noindex-seo-slider"></span>
</label>
<div class="noindex-seo-config-body">
<label for="noindex_seo_config_granular" class="noindex-seo-config-label">
<?php esc_html_e( 'Enable per-post/page granular control', 'noindex-seo' ); ?>
</label>
<p class="description">
<?php esc_html_e( 'When enabled, a meta box will appear in the post/page editor allowing you to override global settings for individual content. Useful for specific pages that need different robots directives.', 'noindex-seo' ); ?>
</p>
</div>
</div>
<div class="noindex-seo-config-option">
<label class="noindex-seo-switch">
<input
type="checkbox"
id="noindex_seo_config_taxonomies_granular"
name="noindex_seo_config_taxonomies_granular"
value="1"
<?php checked( 1, $option_config_taxonomies_granular ); ?>
>
<span class="noindex-seo-slider"></span>
</label>
<div class="noindex-seo-config-body">
<label for="noindex_seo_config_taxonomies_granular" class="noindex-seo-config-label">
<?php esc_html_e( 'Enable per-term granular control', 'noindex-seo' ); ?>
</label>
<p class="description">
<?php esc_html_e( 'When enabled, a "Search Engine Visibility" panel will appear on the Edit screen for every public taxonomy (categories, tags, and custom taxonomies like WooCommerce product categories). Useful for noindexing a specific category or tag without affecting the others.', 'noindex-seo' ); ?>
</p>
</div>
</div>
<div class="noindex-seo-config-option">
<label class="noindex-seo-switch">
<input
type="checkbox"
id="noindex_seo_config_delete_on_uninstall"
name="noindex_seo_config_delete_on_uninstall"
value="1"
<?php checked( 1, $option_config_delete_on_uninstall ); ?>
>
<span class="noindex-seo-slider"></span>
</label>
<div class="noindex-seo-config-body">
<label for="noindex_seo_config_delete_on_uninstall" class="noindex-seo-config-label noindex-seo-config-label-danger">
<?php esc_html_e( 'Delete all plugin data on uninstall', 'noindex-seo' ); ?>
</label>
<p class="description">
<?php esc_html_e( 'When enabled, all settings and per-post robots directives will be permanently deleted when the plugin is uninstalled. By default data is preserved.', 'noindex-seo' ); ?>
</p>
</div>
</div>
</div>
<?php submit_button(); ?>
</form>
<?php endif; ?>
<?php if ( 'settings' === $current_tab ) : ?>
<!-- Recommended settings: one-click defaults. Standalone sibling
form, never nested inside the main settings form (HTML5 forbids
nested <form> elements). -->
<h2 class="noindex-seo-section-title"><?php esc_html_e( 'Recommended settings', 'noindex-seo' ); ?></h2>
<p class="description">
<?php esc_html_e( 'Enables all 5 directives on the 15 contexts flagged "Recommended" (privacy policy, date archives, pagination, search results, attachment pages, previews, 404, WooCommerce cart / checkout / my account). Review and save.', 'noindex-seo' ); ?>
</p>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="noindex-seo-apply-form">
<input type="hidden" name="action" value="noindex_seo_apply_suggestions">
<?php wp_nonce_field( 'noindex_seo_apply_suggestions_nonce' ); ?>
<?php
submit_button(
__( 'Apply Recommended Defaults', 'noindex-seo' ),
'secondary',
'noindex-seo-apply-suggestions',
false,
array(
'title' => __( 'Enable all directives for the 15 contexts flagged as recommended.', 'noindex-seo' ),
)
);
?>
</form>
<!-- Directive grid form (scoped to the settings tab): stats, alert,
search, section cards, submit. -->
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
<input type="hidden" name="action" value="update_noindex_seo">
<input type="hidden" name="noindex_seo_form_scope" value="settings">
<?php wp_nonce_field( 'update_noindex_seo_nonce' ); ?>
<!-- Overview: the number cards. -->
<h2 class="noindex-seo-section-title"><?php esc_html_e( 'Overview', 'noindex-seo' ); ?></h2>
<div class="noindex-seo-stats">
<div class="noindex-seo-stat-card">
<div class="noindex-seo-stat-number" id="noindex-seo-stat-total">0</div>
<div class="noindex-seo-stat-label"><?php esc_html_e( 'Total Options', 'noindex-seo' ); ?></div>
</div>
<div class="noindex-seo-stat-card">
<div class="noindex-seo-stat-number" id="noindex-seo-stat-enabled">0</div>
<div class="noindex-seo-stat-label"><?php esc_html_e( 'Enabled', 'noindex-seo' ); ?></div>
</div>
<div class="noindex-seo-stat-card">
<div class="noindex-seo-stat-number" id="noindex-seo-stat-recommended">0</div>
<div class="noindex-seo-stat-label"><?php esc_html_e( 'Recommended to Enable', 'noindex-seo' ); ?></div>
</div>
</div>
<!-- Page contexts: the directive grid. -->
<h2 class="noindex-seo-section-title"><?php esc_html_e( 'Page contexts', 'noindex-seo' ); ?></h2>
<!-- Alert -->
<div class="noindex-seo-alert">
<span class="dashicons dashicons-warning"></span>
<p><?php esc_html_e( 'Important: Enabling noindex on the wrong pages can harm your search engine rankings. Only enable options you fully understand.', 'noindex-seo' ); ?></p>
</div>
<!-- Search Box -->
<div class="noindex-seo-search">
<input
type="search"
placeholder="<?php esc_attr_e( 'Search options...', 'noindex-seo' ); ?>"
aria-label="<?php esc_attr_e( 'Search options', 'noindex-seo' ); ?>"
>
</div>
<!-- Sections as Cards -->
<?php foreach ( $sections as $section_id => $section ) : ?>
<?php
// Default icon when a dynamically-added section (e.g. 'custom_post_types'
// added in 3.1.0) doesn't have an entry in the static $section_icons map.
$icon = isset( $section_icons[ $section_id ] ) ? $section_icons[ $section_id ] : 'dashicons-admin-generic';
?>
<div class="noindex-seo-card" id="noindex-seo-card-<?php echo esc_attr( $section_id ); ?>">
<div class="noindex-seo-card-header">
<h3>
<span class="dashicons <?php echo esc_attr( $icon ); ?>"></span>
<?php echo esc_html( $section['title'] ); ?>
</h3>
<span class="dashicons dashicons-arrow-down-alt2 noindex-seo-card-toggle"></span>
</div>
<div class="noindex-seo-card-body">
<?php foreach ( $section['fields'] as $field_id => $field ) : ?>
<?php
// Check if field should be disabled (header-only fields with meta method).
$should_disable = in_array( $field_id, $header_only_fields, true ) && ! $is_header_enabled;
?>
<div class="noindex-seo-option<?php echo $should_disable ? ' disabled' : ''; ?>"<?php echo $should_disable ? ' title="' . esc_attr__( 'This option only works with HTTP Headers implementation method', 'noindex-seo' ) . '"' : ''; ?>>
<div class="noindex-seo-option-header">
<div class="noindex-seo-option-title">
<strong><?php echo esc_html( $field['label'] ); ?></strong>
<span class="noindex-seo-badge <?php echo $field['suggestion'] ? 'recommended' : 'not-recommended'; ?>">
<?php
if ( $field['suggestion'] ) {
esc_html_e( 'Recommended', 'noindex-seo' );
} else {
esc_html_e( 'Not Recommended', 'noindex-seo' );
}
?>
</span>
<?php if ( isset( $field['view_url'] ) && ! empty( $field['view_url'] ) ) : ?>
<a href="<?php echo esc_url( $field['view_url'] ); ?>" target="_blank" class="noindex-seo-view-link" title="<?php esc_attr_e( 'View Page', 'noindex-seo' ); ?>">
<span class="dashicons dashicons-external"></span>
</a>
<?php endif; ?>
</div>
<p class="noindex-seo-option-description">
<?php echo esc_html( $field['description'] ); ?>
</p>
</div>
<div class="noindex-seo-directives">
<?php foreach ( $directives_config as $directive => $config ) : ?>
<?php
$directive_option_key = $directive . '_seo_' . $field_id;
$directive_value = noindex_seo_get_setting( $field_id, $directive );
?>
<?php if ( 'bool' === $config['type'] ) : ?>
<label class="noindex-seo-directive-checkbox">
<input
type="checkbox"
id="<?php echo esc_attr( $directive_option_key ); ?>"
name="<?php echo esc_attr( $directive_option_key ); ?>"
value="1"
<?php checked( 1, $directive_value ); ?>
<?php disabled( $should_disable ); ?>
>
<span class="directive-icon"><?php echo noindex_seo_get_directive_icon_html( $directive ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from the plugin's own icon registry, or the escaped emoji fallback. ?></span>
<span class="directive-label"><?php echo esc_html( $config['label'] ); ?></span>
<span class="directive-description"><?php echo esc_html( $config['desc'] ); ?></span>
</label>
<?php elseif ( 'int' === $config['type'] ) : ?>
<label class="noindex-seo-directive-checkbox noindex-seo-directive-value">
<input
type="number"
min="-1"
step="1"
placeholder="<?php esc_attr_e( 'Off', 'noindex-seo' ); ?>"
id="<?php echo esc_attr( $directive_option_key ); ?>"
name="<?php echo esc_attr( $directive_option_key ); ?>"
value="<?php echo esc_attr( (string) $directive_value ); ?>"
<?php disabled( $should_disable ); ?>
>
<span class="directive-label"><?php echo esc_html( $config['label'] ); ?></span>
<span class="directive-description"><?php echo esc_html( $config['desc'] ); ?></span>
</label>
<?php elseif ( 'preview' === $config['type'] ) : ?>
<label class="noindex-seo-directive-checkbox noindex-seo-directive-value">
<select
id="<?php echo esc_attr( $directive_option_key ); ?>"
name="<?php echo esc_attr( $directive_option_key ); ?>"
<?php disabled( $should_disable ); ?>
>
<option value="" <?php selected( '', (string) $directive_value ); ?>><?php esc_html_e( 'Off', 'noindex-seo' ); ?></option>
<option value="none" <?php selected( 'none', (string) $directive_value ); ?>><?php esc_html_e( 'none', 'noindex-seo' ); ?></option>
<option value="standard" <?php selected( 'standard', (string) $directive_value ); ?>><?php esc_html_e( 'standard', 'noindex-seo' ); ?></option>
<option value="large" <?php selected( 'large', (string) $directive_value ); ?>><?php esc_html_e( 'large', 'noindex-seo' ); ?></option>
</select>
<span class="directive-label"><?php echo esc_html( $config['label'] ); ?></span>
<span class="directive-description"><?php echo esc_html( $config['desc'] ); ?></span>
</label>
<?php else : ?>
<label class="noindex-seo-directive-checkbox noindex-seo-directive-value">
<input
type="datetime-local"
id="<?php echo esc_attr( $directive_option_key ); ?>"
name="<?php echo esc_attr( $directive_option_key ); ?>"
value="<?php echo esc_attr( str_replace( ' ', 'T', (string) $directive_value ) ); ?>"
<?php disabled( $should_disable ); ?>
>
<span class="directive-label"><?php echo esc_html( $config['label'] ); ?></span>
<span class="directive-description"><?php echo esc_html( $config['desc'] ); ?></span>
</label>
<?php endif; ?>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>
<!-- Conditional auto-noindex rules (3.6.0). -->
<h2 class="noindex-seo-section-title"><?php esc_html_e( 'Conditional rules', 'noindex-seo' ); ?></h2>
<p class="description">
<?php esc_html_e( 'Automatically apply noindex to any post whose custom field (for example an ACF field) exactly matches a value. Rules run below the per-post overrides and above the global context settings, and matched posts drop out of the XML sitemap.', 'noindex-seo' ); ?>
</p>
<div class="noindex-seo-card" id="noindex-seo-card-rules">
<div class="noindex-seo-card-header">
<h3>
<span class="dashicons dashicons-filter"></span>
<?php esc_html_e( 'Conditional rules', 'noindex-seo' ); ?>
</h3>
<span class="dashicons dashicons-arrow-down-alt2 noindex-seo-card-toggle"></span>
</div>
<div class="noindex-seo-card-body">
<div class="noindex-seo-rules-table">
<div class="noindex-seo-rule-row noindex-seo-rule-head">
<span><?php esc_html_e( 'Field name', 'noindex-seo' ); ?></span>
<span><?php esc_html_e( 'Value', 'noindex-seo' ); ?></span>
<span class="screen-reader-text"><?php esc_html_e( 'Actions', 'noindex-seo' ); ?></span>
</div>
<div class="noindex-seo-rule-rows" data-max-rules="20">
<?php $rules = noindex_seo_get_settings()['rules']; ?>
<?php if ( empty( $rules ) ) : ?>
<?php
$rules = array(
array(
'field' => '',
'value' => '',
),
); // One empty row for the first rule.
?>
<?php endif; ?>
<?php foreach ( $rules as $rule ) : ?>
<div class="noindex-seo-rule-row">
<input type="text" name="noindex_seo_rule_field[]" value="<?php echo esc_attr( $rule['field'] ); ?>" placeholder="<?php esc_attr_e( 'custom_field_name', 'noindex-seo' ); ?>">
<input type="text" name="noindex_seo_rule_value[]" value="<?php echo esc_attr( $rule['value'] ); ?>" placeholder="<?php esc_attr_e( 'value that triggers noindex', 'noindex-seo' ); ?>">
<button type="button" class="button noindex-seo-rule-remove" aria-label="<?php esc_attr_e( 'Remove rule', 'noindex-seo' ); ?>"><span class="dashicons dashicons-no-alt"></span></button>
</div>
<?php endforeach; ?>
</div>
<p>
<button type="button" class="button noindex-seo-rule-add"><?php esc_html_e( 'Add rule', 'noindex-seo' ); ?></button>
<span class="description"><?php esc_html_e( 'Up to 20 rules. Rows with an empty field or value are ignored.', 'noindex-seo' ); ?></span>
</p>
</div>
</div>
</div>
<?php submit_button(); ?>
</form>
<?php endif; ?>
<?php if ( 'tools' === $current_tab ) : ?>
<?php
// Result notices for the plugin import (set by our own admin-post
// handler after a nonce check; display-only query flags).
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only result flags set by our own handler.
$imported_posts = isset( $_GET['plugin_import_posts'] ) && is_numeric( $_GET['plugin_import_posts'] ) ? absint( $_GET['plugin_import_posts'] ) : 0;
$imported_terms = isset( $_GET['plugin_import_terms'] ) && is_numeric( $_GET['plugin_import_terms'] ) ? absint( $_GET['plugin_import_terms'] ) : 0;
$skipped_posts = isset( $_GET['plugin_import_skipped_posts'] ) && is_numeric( $_GET['plugin_import_skipped_posts'] ) ? absint( $_GET['plugin_import_skipped_posts'] ) : 0;
$skipped_terms = isset( $_GET['plugin_import_skipped_terms'] ) && is_numeric( $_GET['plugin_import_skipped_terms'] ) ? absint( $_GET['plugin_import_skipped_terms'] ) : 0;
$import_selection_empty = isset( $_GET['plugin_import_empty'] );
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ( $imported_posts || $imported_terms ) {
$imported_posts_text = sprintf(
/* translators: %d: number of posts. */
_n( 'Imported robots overrides for %d post', 'Imported robots overrides for %d posts', $imported_posts, 'noindex-seo' ),
$imported_posts
);
$imported_terms_text = sprintf(
/* translators: %d: number of terms. */
_n( '%d term', '%d terms', $imported_terms, 'noindex-seo' ),
$imported_terms
);
echo '<div class="notice notice-success is-dismissible"><p>';
echo esc_html( $imported_posts_text . ', ' . $imported_terms_text );
if ( $skipped_posts || $skipped_terms ) {
echo ' — ' . esc_html(
sprintf(
/* translators: 1: number of skipped posts, 2: number of skipped terms. */
__( '%1$d posts and %2$d terms skipped (already configured)', 'noindex-seo' ),
$skipped_posts,
$skipped_terms
)
);
}
echo '</p></div>';
}
if ( $import_selection_empty ) {
echo '<div class="notice notice-warning is-dismissible"><p>';
esc_html_e( 'No plugins were selected to import from.', 'noindex-seo' );
echo '</p></div>';
}
if ( isset( $_GET['plugin_import_done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only result flag set by our own handler after a nonce check.
echo '<div class="notice notice-warning is-dismissible"><p>';
esc_html_e( 'The selected plugins had no importable robots data left.', 'noindex-seo' );
echo '</p></div>';
}
?>
<!-- Import from other plugins: on-demand migration of robots overrides. -->
<h2 class="noindex-seo-section-title"><?php esc_html_e( 'Import from other plugins', 'noindex-seo' ); ?></h2>
<p class="description">
<?php esc_html_e( 'Imports the noindex and nofollow flags stored by other SEO plugins (Yoast SEO, Rank Math, SEOPress, All in One SEO) as per-post and per-term overrides. Nothing is imported automatically: you pick the plugins below and confirm. Content that already has its own override is never touched.', 'noindex-seo' ); ?>
</p>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="noindex-seo-apply-form">
<input type="hidden" name="action" value="noindex_seo_plugin_import">
<?php wp_nonce_field( 'noindex_seo_plugin_import' ); ?>
<?php $import_counts = noindex_seo_count_import_sources(); ?>
<?php $any_importable = false; ?>
<?php foreach ( $import_counts as $import_slug => $import_count ) : ?>
<?php if ( $import_count['posts'] || $import_count['terms'] ) : ?>
<?php $any_importable = true; ?>
<p>
<label>
<input type="checkbox" name="noindex_seo_import_sources[]" value="<?php echo esc_attr( $import_slug ); ?>" checked>
<strong><?php echo esc_html( $import_count['label'] ); ?></strong>
—
<?php
echo esc_html(
sprintf(
/* translators: %d: number of posts found. */
_n( '%d post', '%d posts', $import_count['posts'], 'noindex-seo' ),
$import_count['posts']
)
);
?>
<?php if ( $import_count['terms'] ) : ?>
,
<?php
echo esc_html(
sprintf(
/* translators: %d: number of terms found. */
_n( '%d term', '%d terms', $import_count['terms'], 'noindex-seo' ),
$import_count['terms']
)
);
?>
<?php endif; ?>
</label>
</p>
<?php endif; ?>
<?php endforeach; ?>
<?php if ( ! $any_importable ) : ?>
<p><em><?php esc_html_e( 'No importable robots data from other SEO plugins was found on this site.', 'noindex-seo' ); ?></em></p>
<?php else : ?>
<?php
submit_button(
__( 'Import selected plugins', 'noindex-seo' ),
'secondary',
'noindex-seo-plugin-import',
false
);
?>
<?php endif; ?>
</form>
<!-- Export: download the current settings as a JSON file. -->
<h2 class="noindex-seo-section-title"><?php esc_html_e( 'Export settings', 'noindex-seo' ); ?></h2>
<p class="description">
<?php esc_html_e( 'Download the current settings as a JSON file.', 'noindex-seo' ); ?>
</p>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="noindex-seo-apply-form">
<input type="hidden" name="action" value="noindex_seo_export">
<?php wp_nonce_field( 'noindex_seo_export' ); ?>
<?php
submit_button(
__( 'Export settings', 'noindex-seo' ),
'secondary',
'noindex-seo-export',
false
);
?>
</form>
<!-- Import: restore the global settings from a previous export. -->
<h2 class="noindex-seo-section-title"><?php esc_html_e( 'Import settings', 'noindex-seo' ); ?></h2>
<p class="description">
<?php esc_html_e( 'Restore the global settings from a previously exported JSON file. Per-post and per-term overrides are kept.', 'noindex-seo' ); ?>
</p>
<form method="post" enctype="multipart/form-data" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="noindex-seo-apply-form">
<input type="hidden" name="action" value="noindex_seo_import">
<?php wp_nonce_field( 'noindex_seo_import' ); ?>
<label for="noindex_seo_import_file" class="noindex-seo-config-label">
<?php esc_html_e( 'Import settings', 'noindex-seo' ); ?>
</label>
<input
type="file"
id="noindex_seo_import_file"
name="noindex_seo_import_file"
accept=".json,application/json"
>
<?php
submit_button(
__( 'Import settings', 'noindex-seo' ),
'secondary',
'noindex-seo-import',
false
);
?>
</form>
<?php endif; ?>
<?php if ( 'robotstxt' === $current_tab ) : ?>
<!-- Virtual robots.txt management (3.7.0): extends, never replaces,
the robots.txt WordPress generates virtually. Inactive by default. -->
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
<input type="hidden" name="action" value="update_noindex_seo">
<input type="hidden" name="noindex_seo_form_scope" value="robotstxt">
<?php wp_nonce_field( 'update_noindex_seo_nonce' ); ?>
<div class="noindex-seo-config-option">
<label class="noindex-seo-switch">
<input
type="checkbox"
id="noindex_seo_robotstxt_enabled"
name="noindex_seo_robotstxt_enabled"
value="1"
<?php checked( 1, noindex_seo_get_settings()['robots_txt']['enabled'] ); ?>
>
<span class="noindex-seo-slider"></span>
</label>
<div class="noindex-seo-config-body">
<label for="noindex_seo_robotstxt_enabled" class="noindex-seo-config-label">
<?php esc_html_e( 'Extend the virtual robots.txt with bot rules', 'noindex-seo' ); ?>
</label>
<p class="description">
<?php esc_html_e( 'Inactive by default. When enabled, the rules below are appended to the robots.txt that WordPress generates virtually — they never replace it. This only applies when WordPress serves robots.txt itself: a physical robots.txt file in the site root, or "Discourage search engines" in Reading settings, takes precedence.', 'noindex-seo' ); ?>
</p>
</div>
</div>
<div class="noindex-seo-rules-table noindex-seo-robotstxt-table">
<div class="noindex-seo-rule-row noindex-seo-rule-head">
<span><?php esc_html_e( 'User-agent', 'noindex-seo' ); ?></span>
<span><?php esc_html_e( 'Policy', 'noindex-seo' ); ?></span>
<span class="screen-reader-text"><?php esc_html_e( 'Actions', 'noindex-seo' ); ?></span>
</div>
<div class="noindex-seo-rule-rows noindex-seo-robotstxt-rows" data-max-rules="30">
<?php $robotstxt_rules = noindex_seo_get_settings()['robots_txt']['rules']; ?>
<?php if ( empty( $robotstxt_rules ) ) : ?>
<?php
$robotstxt_rules = array(
array(
'user_agent' => '',
'policy' => 'block',
),
); // One empty row to start from.
?>
<?php endif; ?>
<?php foreach ( $robotstxt_rules as $robotstxt_rule ) : ?>
<div class="noindex-seo-rule-row">
<input type="text" maxlength="100" name="noindex_seo_robotstxt_agent[]" value="<?php echo esc_attr( $robotstxt_rule['user_agent'] ); ?>" placeholder="<?php esc_attr_e( 'User-agent token, e.g. GPTBot or *', 'noindex-seo' ); ?>">
<select name="noindex_seo_robotstxt_policy[]">
<option value="block" <?php selected( 'block', $robotstxt_rule['policy'] ); ?>><?php esc_html_e( 'Block (Disallow: /)', 'noindex-seo' ); ?></option>
<option value="allow" <?php selected( 'allow', $robotstxt_rule['policy'] ); ?>><?php esc_html_e( 'Allow (Allow: /)', 'noindex-seo' ); ?></option>
</select>
<button type="button" class="button noindex-seo-rule-remove" aria-label="<?php esc_attr_e( 'Remove rule', 'noindex-seo' ); ?>"><span class="dashicons dashicons-no-alt"></span></button>
</div>
<?php endforeach; ?>
</div>
<p>
<button type="button" class="button noindex-seo-rule-add" data-target=".noindex-seo-robotstxt-rows"><?php esc_html_e( 'Add rule', 'noindex-seo' ); ?></button>
<button type="button" class="button noindex-seo-robotstxt-preset" data-preset="ai"><?php esc_html_e( 'Add common AI bots', 'noindex-seo' ); ?></button>
<button type="button" class="button noindex-seo-robotstxt-preset" data-preset="search"><?php esc_html_e( 'Add common search engine bots', 'noindex-seo' ); ?></button>
</p>
<p class="description">
<?php esc_html_e( 'Up to 30 rules. Blocked bots receive "Disallow: /" for the whole site; allowed bots receive "Allow: /" (useful to allow one crawler inside a broader block set with a * rule). Duplicate user-agents are ignored.', 'noindex-seo' ); ?>
</p>
</div>
<?php $robotstxt_block = noindex_seo_get_robots_txt_block(); ?>
<?php if ( '' !== $robotstxt_block ) : ?>
<h2 class="noindex-seo-section-title"><?php esc_html_e( 'Preview of the appended block', 'noindex-seo' ); ?></h2>
<pre class="noindex-seo-robotstxt-preview"><code><?php echo esc_html( $robotstxt_block ); ?></code></pre>
<?php endif; ?>
<?php submit_button(); ?>
</form>
<?php endif; ?>
</div>
<?php
}