This commit is contained in:
2026-10-06 18:51:23 -06:00
parent 8424dacd03
commit e2c26b7f21
4223 changed files with 737986 additions and 53 deletions
@@ -0,0 +1,263 @@
<?php
/**
* Ability: rank-math/create-ai-visibility-brand
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use WP_REST_Request;
use RankMath\Abilities\Ability_Interface;
use RankMath\AI_Visibility\Platforms;
use RankMath\AI_Visibility\Api\Brands_Controller;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/create-ai-visibility-brand ability.
*/
class Create_AI_Visibility_Brand implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Brands REST controller instance.
*
* @var Brands_Controller
*/
private $controller;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Brands_Controller|null $controller Controller instance.
*/
public function __construct( string $category, array $shared_meta, ?Brands_Controller $controller = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->controller = $controller ?? new Brands_Controller();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/create-ai-visibility-brand',
[
'category' => $this->category,
'label' => esc_html__( 'Create AI Visibility brand', 'seo-by-rank-math' ),
'description' => sprintf(
/* translators: %s: supported platform IDs. */
esc_html__(
'Creates a new brand for AI Visibility monitoring, triggering an initial analysis automatically. Ask which AI platforms to track. Supported platforms: %s. Selecting more than one requires the Expert plan; other plans may choose only one.',
'seo-by-rank-math'
),
Platforms::supported_as_string()
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'name', 'url', 'language', 'platforms' ],
'properties' => [
'name' => [
'type' => 'string',
'description' => esc_html__( 'Brand name.', 'seo-by-rank-math' ),
],
'url' => [
'type' => 'string',
'format' => 'uri',
'description' => esc_html__( 'Brand website URL.', 'seo-by-rank-math' ),
],
'description' => [
'type' => 'string',
'description' => esc_html__( 'Short description of the brand or product.', 'seo-by-rank-math' ),
'default' => '',
],
'locale' => [
'type' => 'string',
'description' => esc_html__( 'ISO 3166-1 alpha-2 country code (e.g. "US", "HU"). Defaults to no country filter.', 'seo-by-rank-math' ),
'default' => '',
],
'language' => [
'type' => 'string',
'description' => esc_html__( 'Language the brand should be analyzed in (e.g. "US English", "French"). Required; immutable after creation — ask the user which language to use.', 'seo-by-rank-math' ),
'enum' => Brands_Controller::get_language_choices( false ),
],
'interval' => [
'type' => 'string',
'description' => esc_html__( 'Analysis refresh cadence. Defaults to the account plan\'s default when omitted.', 'seo-by-rank-math' ),
'enum' => array_merge( [ '' ], Brands_Controller::get_interval_choices() ),
'default' => '',
],
'platforms' => [
'type' => 'array',
'minItems' => 1,
'description' => sprintf(
/* translators: %s: supported platform IDs. */
esc_html__( 'AI platforms to track. Supported: %s. Selecting more than one requires the Expert plan; otherwise choose exactly one. Do not assume a default — ask the user which platform(s) to use.', 'seo-by-rank-math' ),
Platforms::supported_as_string()
),
'items' => [
'type' => 'string',
'enum' => Platforms::supported(),
],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => false,
'destructive' => false,
'idempotent' => false,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$platforms = $this->validate_platforms( $input['platforms'] ?? null );
if ( isset( $platforms['error'] ) ) {
return $platforms;
}
$request = new WP_REST_Request( 'POST' );
$request->set_param( 'name', sanitize_text_field( (string) ( $input['name'] ?? '' ) ) );
$request->set_param( 'url', esc_url_raw( (string) ( $input['url'] ?? '' ) ) );
$request->set_param( 'description', sanitize_textarea_field( (string) ( $input['description'] ?? '' ) ) );
$request->set_param( 'locale', sanitize_text_field( (string) ( $input['locale'] ?? '' ) ) );
$request->set_param( 'language', sanitize_text_field( (string) ( $input['language'] ?? '' ) ) );
$request->set_param( 'interval', sanitize_text_field( (string) ( $input['interval'] ?? '' ) ) );
$request->set_param( 'platforms', $platforms );
$response = $this->controller->create_brand( $request );
if ( is_wp_error( $response ) ) {
return [ 'error' => $response->get_error_message() ];
}
$data = $response->get_data();
$brand = $data['data']['brand'] ?? [];
return [
'id' => $brand['id'] ?? '',
'name' => $brand['name'] ?? '',
'url' => $brand['url'] ?? '',
'interval' => $brand['interval'] ?? null,
'platforms' => $brand['platforms'] ?? [],
'analysis_status' => 'pending',
'created_at' => $brand['created_at'] ?? null,
];
}
/**
* Sanitize and validate platforms. No silent defaults.
*
* @param mixed $platforms Raw platforms value.
* @return string[]|array{error: string}
*/
private function validate_platforms( $platforms ) {
$valid = Platforms::validate( $platforms );
if ( is_wp_error( $valid ) ) {
return [ 'error' => $valid->get_error_message() ];
}
return Platforms::sanitize( $platforms );
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'string',
'description' => 'UUID of the newly created brand. Use this as brand_id in subsequent ability calls.',
],
'name' => [
'type' => 'string',
'description' => 'Brand name.',
],
'url' => [
'type' => 'string',
'format' => 'uri',
'description' => 'Brand website URL.',
],
'interval' => [
'type' => [ 'string', 'null' ],
'enum' => array_merge( [ null ], Brands_Controller::get_interval_choices() ),
'description' => 'Resolved analysis cadence for this brand.',
],
'platforms' => [
'type' => 'array',
'description' => 'AI platforms selected for this brand.',
'items' => [
'type' => 'string',
'enum' => Platforms::supported(),
],
],
'analysis_status' => [
'type' => 'string',
'enum' => [ 'pending' ],
'description' => 'Always "pending" on creation — the initial analysis is seeded automatically and will complete asynchronously.',
],
'created_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the brand was created.',
],
'error' => [
'type' => 'string',
'description' => 'Present only on failure — human-readable error from validation or the upstream API.',
],
],
];
}
}
@@ -0,0 +1,286 @@
<?php
/**
* Ability: rank-math/get-ai-visibility-brand-insights
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use RankMath\Abilities\Ability_Interface;
use RankMath\AI_Visibility\Cache;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-ai-visibility-brand-insights ability.
*/
class Get_AI_Visibility_Brand_Insights implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-ai-visibility-brand-insights',
[
'category' => $this->category,
'label' => esc_html__( 'Get AI Visibility brand insights', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the full analysis results for a single brand — AI Visibility score, rank, sentiment, mention and citation counts, per-competitor breakdown, and per-query results including the raw AI model responses.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'brand_id' ],
'properties' => [
'brand_id' => [
'type' => 'string',
'description' => esc_html__( 'Brand UUID. Obtain from get-ai-visibility-overview.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$brand_id = sanitize_text_field( (string) ( $input['brand_id'] ?? '' ) );
$cached = Cache::get_analysis( $brand_id );
if ( false === $cached || Cache::is_brand_stale( $brand_id ) ) {
rank_math()->tracking->track_ability_executed(
'AI Visibility Brand Insights Fetched',
[
'brand_id' => $brand_id,
'pending' => true,
'query_count' => 0,
'competitor_count' => 0,
],
'manage_options'
);
return [ 'pending' => true ];
}
$query_count = count( $cached['query_results'] ?? [] );
$competitor_count = count( $cached['competitors'] ?? [] );
rank_math()->tracking->track_ability_executed(
'AI Visibility Brand Insights Fetched',
[
'brand_id' => $brand_id,
'pending' => false,
'query_count' => $query_count,
'competitor_count' => $competitor_count,
],
'manage_options'
);
return array_merge( $cached, [ 'pending' => false ] );
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'pending' => [
'type' => 'boolean',
'description' => 'True when no completed analysis exists yet (e.g. brand was just added). All other fields are absent in this case.',
],
'score' => [
'type' => [ 'number', 'null' ],
'description' => 'AI Visibility score for this brand.',
],
'rank' => [
'type' => [ 'number', 'null' ],
'description' => 'Brand ranking position among competitors.',
],
'avg_sentiment' => [
'type' => [ 'number', 'null' ],
'description' => 'Average sentiment score across all mentions.',
],
'mentions' => [
'type' => [ 'number', 'null' ],
'description' => 'Total number of AI mentions.',
],
'citations' => [
'type' => [ 'number', 'null' ],
'description' => 'Total number of AI citations.',
],
'analyses' => [
'type' => 'array',
'description' => 'The latest completed analysis for each tracked AI platform (one entry per platform).',
'items' => [
'type' => 'object',
'properties' => [
'id' => [
'type' => [ 'string', 'null' ],
'description' => 'Analysis UUID.',
],
'platform' => [
'type' => [ 'string', 'null' ],
'description' => 'AI platform this analysis ran on (e.g. chatgpt, gemini).',
],
'status' => [
'type' => [ 'string', 'null' ],
'description' => 'Analysis status (e.g. done, processing, error).',
],
'started_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the analysis started.',
],
'finished_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the analysis completed.',
],
'duration_seconds' => [
'type' => [ 'number', 'null' ],
'description' => 'How long the analysis took in seconds.',
],
],
],
],
'competitors' => [
'type' => 'array',
'description' => 'Per-competitor breakdown for this brand.',
'items' => [
'type' => 'object',
'properties' => [
'name' => [
'type' => 'string',
'description' => 'Competitor brand name.',
],
'url' => [
'type' => [ 'string', 'null' ],
'format' => 'uri',
'description' => 'Competitor website URL.',
],
'mentions' => [
'type' => [ 'number', 'null' ],
'description' => 'Number of AI mentions for this competitor.',
],
'avg_sentiment' => [
'type' => [ 'number', 'null' ],
'description' => 'Average sentiment score for this competitor.',
],
],
],
],
'query_results' => [
'type' => 'array',
'description' => 'Per-query analysis results including raw AI model responses.',
'items' => [
'type' => 'object',
'properties' => [
'query_id' => [
'type' => [ 'string', 'null' ],
'description' => 'Query UUID.',
],
'query_text' => [
'type' => 'string',
'description' => 'The query that was submitted to the AI model.',
],
'platform' => [
'type' => [ 'string', 'null' ],
'description' => 'AI platform that produced this result (e.g. chatgpt, gemini).',
],
'found' => [
'type' => 'boolean',
'description' => 'Whether the brand was mentioned in the AI response.',
],
'rank' => [
'type' => [ 'number', 'null' ],
'description' => 'Brand rank among competitors for this query.',
],
'sentiment' => [
'type' => [ 'number', 'null' ],
'description' => 'Sentiment score for the brand mention in this query.',
],
'citations' => [
'type' => [ 'number', 'null' ],
'description' => 'Number of citations in the AI response for this query.',
],
'response' => [
'type' => 'string',
'description' => 'Raw text response returned by the AI model for this query.',
],
'extraction_data' => [
'type' => 'string',
'description' => 'Raw extraction data used to derive the structured results.',
],
],
],
],
],
];
}
}
@@ -0,0 +1,195 @@
<?php
/**
* Ability: rank-math/get-ai-visibility-brand-queries
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use RankMath\Abilities\Ability_Interface;
use RankMath\AI_Visibility\Cache;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-ai-visibility-brand-queries ability.
*/
class Get_AI_Visibility_Brand_Queries implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-ai-visibility-brand-queries',
[
'category' => $this->category,
'label' => esc_html__( 'Get AI Visibility brand queries', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the list of search queries being monitored for a brand, including which are currently enabled and which were auto-generated as baselines.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'brand_id' ],
'properties' => [
'brand_id' => [
'type' => 'string',
'description' => esc_html__( 'Brand UUID. Obtain from get-ai-visibility-overview or get-ai-visibility-brand-insights.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$brand_id = sanitize_text_field( (string) ( $input['brand_id'] ?? '' ) );
$cached = Cache::get_queries( $brand_id );
$queries = null !== $cached ? (array) ( $cached['queries'] ?? [] ) : [];
$total = count( $queries );
$enabled_count = count(
array_filter(
$queries,
function ( $q ) {
return ! empty( $q['enabled'] );
}
)
);
rank_math()->tracking->track_ability_executed(
'AI Visibility Brand Queries Fetched',
[
'brand_id' => $brand_id,
'total' => $total,
'enabled_count' => $enabled_count,
],
'manage_options'
);
return [
'brand_id' => $brand_id,
'queries' => $queries,
'total' => $total,
];
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'brand_id' => [
'type' => 'string',
'description' => 'The brand UUID the queries belong to.',
],
'queries' => [
'type' => 'array',
'description' => 'List of monitored queries for this brand.',
'items' => [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'string',
'description' => 'Query UUID.',
],
'text' => [
'type' => 'string',
'description' => 'The query text submitted to AI models.',
],
'enabled' => [
'type' => 'boolean',
'description' => 'Whether this query is currently active for analysis.',
],
'is_baseline' => [
'type' => 'boolean',
'description' => 'True when this query was auto-generated as a baseline by Rank Math.',
],
'created_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the query was created.',
],
'updated_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the query was last updated.',
],
],
],
],
'total' => [
'type' => 'integer',
'description' => 'Total number of queries returned.',
],
],
];
}
}
@@ -0,0 +1,233 @@
<?php
/**
* Ability: rank-math/get-ai-visibility-overview
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use RankMath\Abilities\Ability_Interface;
use RankMath\AI_Visibility\Cache;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-ai-visibility-overview ability.
*/
class Get_AI_Visibility_Overview implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-ai-visibility-overview',
[
'category' => $this->category,
'label' => esc_html__( 'Get AI Visibility overview', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the site-level AI Visibility summary and the full list of tracked brands with their current scores, ranks, sentiment, and analysis status.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'refresh' => [
'type' => 'boolean',
'description' => esc_html__( 'Pass true to bypass the 12-hour dashboard cache and return a stale-flagged response. Use the REST endpoint to trigger a fresh upstream fetch.', 'seo-by-rank-math' ),
'default' => false,
],
'search' => [
'type' => 'string',
'description' => esc_html__( 'Filter brands by name or URL (case-insensitive substring match).', 'seo-by-rank-math' ),
'default' => '',
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$refresh = (bool) ( $input['refresh'] ?? false );
$search = sanitize_text_field( (string) ( $input['search'] ?? '' ) );
$data = Cache::get_dashboard();
$summary = isset( $data['summary'] ) ? (array) $data['summary'] : [];
$brands = isset( $data['brands'] ) ? (array) $data['brands'] : [];
if ( '' !== $search ) {
$brands = array_values(
array_filter(
$brands,
function ( $row ) use ( $search ) {
return false !== stripos( $row['name'] ?? '', $search )
|| false !== stripos( $row['url'] ?? '', $search );
}
)
);
}
// Strip internal cache fields not relevant to MCP consumers.
$brands = array_map(
function ( $row ) {
unset( $row['stale'], $row['next_scheduled'], $row['created_at'] );
return $row;
},
$brands
);
rank_math()->tracking->track_ability_executed(
'AI Visibility Overview Fetched',
[
'brand_count' => count( $brands ),
'refresh' => $refresh,
],
'manage_options'
);
return [
'summary' => $summary,
'brands' => $brands,
];
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'summary' => [
'type' => 'object',
'description' => 'Site-level AI Visibility summary metrics.',
],
'brands' => [
'type' => 'array',
'description' => 'List of tracked brands with their current AI Visibility data.',
'items' => [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'string',
'description' => 'Brand UUID.',
],
'name' => [
'type' => 'string',
'description' => 'Brand name.',
],
'url' => [
'type' => 'string',
'format' => 'uri',
'description' => 'Brand website URL.',
],
'locale' => [
'type' => [ 'string', 'null' ],
'description' => 'ISO 3166-1 alpha-2 country code (e.g. "US").',
],
'status' => [
'type' => 'string',
'enum' => [ 'active', 'inactive' ],
'description' => 'Whether the brand is actively tracked.',
],
'score' => [
'type' => [ 'number', 'null' ],
'description' => 'AI Visibility score for this brand.',
],
'rank' => [
'type' => [ 'number', 'null' ],
'description' => 'Brand ranking position.',
],
'avg_sentiment' => [
'type' => [ 'number', 'null' ],
'description' => 'Average sentiment score across mentions.',
],
'mentions' => [
'type' => [ 'number', 'null' ],
'description' => 'Total number of AI mentions.',
],
'citations' => [
'type' => [ 'number', 'null' ],
'description' => 'Total number of AI citations.',
],
'analysis_status' => [
'type' => [ 'string', 'null' ],
'description' => 'Current analysis status (e.g. pending, processing, success, error).',
],
'last_analyzed' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime of the last completed analysis.',
],
],
],
],
],
];
}
}
@@ -0,0 +1,109 @@
<?php
/**
* Subscriber for AI Visibility abilities.
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the AI Visibility ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for AI Visibility abilities.
*/
const CATEGORY_SLUG = 'rank-math-ai-visibility';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_ai_visibility_overview' );
$this->action( 'wp_abilities_api_init', 'register_get_ai_visibility_brand_insights' );
$this->action( 'wp_abilities_api_init', 'register_get_ai_visibility_brand_queries' );
$this->action( 'wp_abilities_api_init', 'register_create_ai_visibility_brand' );
}
/**
* Register the AI Visibility ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'AI Visibility', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to retrieve AI brand visibility data tracked by Rank Math.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-ai-visibility-overview ability.
*
* @return void
*/
public function register_get_ai_visibility_overview(): void {
( new Get_AI_Visibility_Overview( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/get-ai-visibility-brand-insights ability.
*
* @return void
*/
public function register_get_ai_visibility_brand_insights(): void {
( new Get_AI_Visibility_Brand_Insights( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/get-ai-visibility-brand-queries ability.
*
* @return void
*/
public function register_get_ai_visibility_brand_queries(): void {
( new Get_AI_Visibility_Brand_Queries( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/create-ai-visibility-brand ability.
*
* @return void
*/
public function register_create_ai_visibility_brand(): void {
( new Create_AI_Visibility_Brand( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,233 @@
<?php
/**
* Ability: rank-math/get-top-keywords
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Analytics
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Analytics;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-top-keywords ability.
*/
class Get_Top_Keywords implements Ability_Interface {
/**
* Maps date_range enum values to Stats::set_date_range() arguments.
*/
const DATE_RANGE_MAP = [
'last_7_days' => '-7 days',
'last_30_days' => '-30 days',
'last_3_months' => '-3 months',
'last_6_months' => '-6 months',
'last_12_months' => '-1 year',
];
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Runner instance.
*
* @var Top_Keywords_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Top_Keywords_Runner|null $runner Runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Top_Keywords_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Top_Keywords_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-top-keywords',
[
'category' => $this->category,
'label' => esc_html__( 'Get top keywords', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the top-performing keywords by clicks from Google Search Console, with impressions, CTR, and average position for the selected date range.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'date_range' => [
'type' => 'string',
'enum' => array_keys( self::DATE_RANGE_MAP ),
'default' => 'last_30_days',
'description' => esc_html__( 'Date range for which to fetch keyword data.', 'seo-by-rank-math' ),
],
'limit' => [
'type' => 'integer',
'default' => 25,
'minimum' => 1,
'maximum' => 100,
'description' => esc_html__( 'Maximum number of keywords to return.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_analytics' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$date_range = isset( $input['date_range'] ) && in_array( $input['date_range'], array_keys( self::DATE_RANGE_MAP ), true )
? (string) $input['date_range']
: 'last_30_days';
$limit = isset( $input['limit'] ) ? max( 1, min( 100, absint( $input['limit'] ) ) ) : 25;
$result = $this->runner->run( $date_range, $limit );
rank_math()->tracking->track_ability_executed(
'Top Keywords Fetched',
[
'limit' => $limit,
'date_range' => $date_range,
],
'rank_math_analytics'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'keywords' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'keyword' => [
'type' => 'string',
'description' => esc_html__( 'The search query keyword.', 'seo-by-rank-math' ),
],
'clicks' => [
'type' => 'integer',
'description' => esc_html__( 'Total clicks from Google Search Console.', 'seo-by-rank-math' ),
],
'impressions' => [
'type' => 'integer',
'description' => esc_html__( 'Total impressions from Google Search Console.', 'seo-by-rank-math' ),
],
'ctr' => [
'type' => 'number',
'description' => esc_html__( 'Click-through rate as a percentage (0–100).', 'seo-by-rank-math' ),
],
'position' => [
'type' => 'number',
'description' => esc_html__( 'Average position in Google Search results.', 'seo-by-rank-math' ),
],
'trend' => [
'type' => 'string',
'enum' => [ 'winning', 'losing', 'stable' ],
'description' => esc_html__( 'Position trend vs. the previous period. Provided by Rank Math PRO for tracked keywords.', 'seo-by-rank-math' ),
],
'is_tracked' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether this keyword is tracked in Rank Math PRO Rank Tracker.', 'seo-by-rank-math' ),
],
'ranking_posts' => [
'type' => 'array',
'description' => esc_html__( 'Pages on your site that rank for this keyword. Provided by Rank Math PRO.', 'seo-by-rank-math' ),
'items' => [
'type' => 'object',
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'WordPress post ID.', 'seo-by-rank-math' ),
],
'title' => [
'type' => 'string',
'description' => esc_html__( 'Post title.', 'seo-by-rank-math' ),
],
'slug' => [
'type' => 'string',
'description' => esc_html__( 'Relative URL path of the page.', 'seo-by-rank-math' ),
],
],
],
],
],
],
],
'date_range' => [
'type' => 'string',
'enum' => array_keys( self::DATE_RANGE_MAP ),
],
'connected' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether Google Search Console is connected.', 'seo-by-rank-math' ),
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Analytics abilities.
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Analytics
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Analytics;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Analytics ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Analytics abilities.
*/
const CATEGORY_SLUG = 'rank-math-analytics';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_top_keywords' );
}
/**
* Register the Analytics ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Analytics', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to query Google Search Console and analytics data.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-top-keywords ability.
*
* @return void
*/
public function register_get_top_keywords(): void {
( new Get_Top_Keywords( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1,101 @@
<?php
/**
* Top-keywords runner for the rank-math/get-top-keywords ability.
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Analytics
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Analytics;
use RankMath\Analytics\Stats;
use RankMath\Google\Console;
defined( 'ABSPATH' ) || exit;
/**
* Fetches top-performing keywords from Google Search Console and shapes the
* result for ability/MCP consumers.
*/
class Top_Keywords_Runner {
/**
* Stats service instance.
*
* @var Stats
*/
private $stats;
/**
* Constructor.
*
* @param Stats|null $stats Stats instance; defaults to the singleton.
*/
public function __construct( ?Stats $stats = null ) {
$this->stats = $stats ?? Stats::get();
}
/**
* Fetch and return the top keywords for the given date range.
*
* The keywords array is passed through the rank_math/analytics/ability/top_keywords
* filter so that the PRO plugin can annotate entries with position-trend data.
*
* @param string $date_range One of the Get_Top_Keywords::DATE_RANGE_MAP keys.
* @param int $limit Maximum number of keywords to return.
* @return array {
* @type array $keywords Flat list of keyword objects.
* @type string $date_range The date_range value that was used.
* @type bool $connected Whether Google Search Console is connected.
* }
*/
public function run( string $date_range, int $limit ): array {
if ( ! Console::is_console_connected() ) {
return [
'keywords' => [],
'date_range' => $date_range,
'connected' => false,
];
}
$range = isset( Get_Top_Keywords::DATE_RANGE_MAP[ $date_range ] )
? Get_Top_Keywords::DATE_RANGE_MAP[ $date_range ]
: Get_Top_Keywords::DATE_RANGE_MAP['last_30_days'];
$this->stats->set_date_range( $range );
$rows = $this->stats->get_analytics_data(
[
'dimension' => 'query',
'orderBy' => 'clicks',
'order' => 'DESC',
'offset' => 0,
'perpage' => $limit,
'objects' => true,
'pageview' => false,
]
);
$keywords = [];
foreach ( $rows as $query => $row ) {
$keywords[] = [
'keyword' => (string) $query,
'clicks' => (int) $row['clicks']['total'],
'impressions' => (int) $row['impressions']['total'],
'ctr' => (float) $row['ctr']['total'],
'position' => (float) $row['position']['total'],
];
}
// PRO plugin hooks here to annotate keywords with position trend data.
$keywords = apply_filters( 'rank_math/analytics/ability/top_keywords', $keywords, $date_range );
return [
'keywords' => $keywords,
'date_range' => $date_range,
'connected' => true,
];
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,105 @@
<?php
/**
* WordPress Abilities API integration for Rank Math SEO.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities;
use RankMath\Abilities\SEO_Analysis\Subscriber as SEO_Analysis_Subscriber;
use RankMath\Abilities\Link_Genius\Subscriber as Link_Genius_Subscriber;
use RankMath\Abilities\Post_SEO\Subscriber as Post_SEO_Subscriber;
use RankMath\Abilities\Schema\Subscriber as Schema_Subscriber;
use RankMath\Abilities\Analytics\Subscriber as Analytics_Subscriber;
use RankMath\Abilities\AI_Visibility\Subscriber as AI_Visibility_Subscriber;
use RankMath\Abilities\Settings\Subscriber as Settings_Subscriber;
use RankMath\Abilities\Content_Analysis\Subscriber as Content_Analysis_Subscriber;
use RankMath\Abilities\Sitemap\Subscriber as Sitemap_Subscriber;
use RankMath\Abilities\Monitor_404\Subscriber as Monitor_404_Subscriber;
use RankMath\Abilities\Redirections\Subscriber as Redirections_Subscriber;
defined( 'ABSPATH' ) || exit;
/**
* Bootstraps Rank Math feature subscribers with the WordPress Abilities API.
*/
class Abilities {
/**
* Singleton instance.
*
* @var Abilities
*/
private static $instance;
/**
* Get singleton.
*
* @return Abilities
*/
public static function get() {
if ( is_null( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor — registers feature subscribers if the Abilities API is available.
*/
public function __construct() {
if ( ! function_exists( 'wp_register_ability' ) ) {
return;
}
$this->register_subscribers();
}
/**
* Instantiate and register all feature subscribers.
*
* @return void
*/
private function register_subscribers() {
$shared_meta = $this->shared_meta();
$subscribers = [
new SEO_Analysis_Subscriber( $shared_meta ),
new Link_Genius_Subscriber( $shared_meta ),
new Post_SEO_Subscriber( $shared_meta ),
new Schema_Subscriber( $shared_meta ),
new Analytics_Subscriber( $shared_meta ),
new AI_Visibility_Subscriber( $shared_meta ),
new Settings_Subscriber( $shared_meta ),
new Content_Analysis_Subscriber( $shared_meta ),
new Sitemap_Subscriber( $shared_meta ),
new Monitor_404_Subscriber( $shared_meta ),
new Redirections_Subscriber( $shared_meta ),
];
foreach ( $subscribers as $subscriber ) {
$subscriber->register();
}
}
/**
* Default meta args shared by every ability we register.
*
* @return array
*/
private function shared_meta() {
return [
'show_in_rest' => true,
'annotations' => [
'readonly' => false,
'destructive' => false,
'idempotent' => true,
],
'mcp' => [ 'public' => true ],
];
}
}
@@ -0,0 +1,266 @@
<?php
/**
* Ability: rank-math/analyze-post-content
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Content_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Content_Analysis;
use RankMath\Abilities\Ability_Interface;
use RankMath\Rest\Rest_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/analyze-post-content ability.
*/
class Analyze_Post_Content implements Ability_Interface {
/**
* KB article covering all 24 on-page SEO tests, used as the scoring rubric reference.
*/
const KB_LINK = 'https://rankmath.com/kb/score-100-in-tests/';
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Content analysis data gatherer.
*
* @var Content_Analysis_Data
*/
private $data;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Content_Analysis_Data|null $data Content analysis data gatherer (injectable for tests).
*/
public function __construct( string $category, array $shared_meta, ?Content_Analysis_Data $data = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->data = $data ?? new Content_Analysis_Data();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/analyze-post-content',
[
'category' => $this->category,
'label' => esc_html__( 'Analyze post content', 'seo-by-rank-math' ),
'description' => esc_html__(
'Gathers the raw content, metadata, and list of on-page SEO tests for a saved post so an AI agent can run Rank Math\'s full on-page analysis itself, since the scoring engine only runs client-side. Use tests_to_run and content together with kb_link (the scoring rubric for all 24 tests) to evaluate each test and produce a per-test score, status, and fix message.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'required' => [ 'post_id' ],
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'ID of the post to analyze.', 'seo-by-rank-math' ),
],
'keyword' => [
'type' => 'string',
'description' => esc_html__( 'Optional focus keyword to analyze against, overriding the post\'s saved focus keyword.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_onpage_analysis' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_id = absint( $input['post_id'] );
$post = get_post( $post_id );
if ( ! $post || ! in_array( get_post_status( $post_id ), [ 'publish', 'draft', 'private', 'pending' ], true ) ) {
return [
'error' => [
'code' => 'invalid_post',
'message' => esc_html__( 'No post found with the given ID, or the post status is not supported.', 'seo-by-rank-math' ),
],
];
}
if ( ! Rest_Helper::can_edit_post( $post ) ) {
return [
'error' => [
'code' => 'rest_cannot_edit',
'message' => esc_html__( 'Sorry, you are not allowed to edit this post.', 'seo-by-rank-math' ),
],
];
}
if ( post_password_required( $post ) ) {
return [
'error' => [
'code' => 'post_password_required',
'message' => esc_html__( 'This post is password protected.', 'seo-by-rank-math' ),
],
];
}
$keyword = isset( $input['keyword'] ) ? sanitize_text_field( $input['keyword'] ) : '';
$payload = $this->data->get( $post, $keyword );
$result = [
'post_id' => $post_id,
'keyword' => $payload['content']['focus_keyword'],
'tests_to_run' => $payload['tests_to_run'],
'content' => $payload['content'],
'kb_link' => self::KB_LINK,
'instructions' => esc_html__(
'Evaluate each test ID in tests_to_run against the fields in content, using kb_link as the scoring rubric for how each test is scored. Return a per-test breakdown with score, max_score, status (pass/fail), and a message with a specific fix. For the contentHasTOC test, when suggesting a fix or drafting content, tell the user to insert the Rank Math Table of Contents block (block name rank-math/toc-block, available in the block inserter as "Table of Contents") right after the intro, instead of a manual list of links — it auto-generates from the post headings.',
'seo-by-rank-math'
),
'error' => null,
];
rank_math()->tracking->track_ability_executed(
'Post Content Analyzed',
[
'post_id' => $post_id,
'tests_count' => count( $payload['tests_to_run'] ),
'has_keyword' => ! empty( $result['keyword'] ),
],
'rank_math_onpage_analysis'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'post_id' => [ 'type' => 'integer' ],
'keyword' => [
'type' => 'string',
'description' => 'Focus keyword used for analysis (input override, or the post\'s saved keyword).',
],
'tests_to_run' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
'description' => 'IDs of the on-page SEO tests registered for this post, to be evaluated by the caller.',
],
'content' => [
'type' => 'object',
'description' => 'Raw content and metadata needed to evaluate each test in tests_to_run.',
'properties' => [
'title' => [ 'type' => 'string' ],
'description' => [ 'type' => 'string' ],
'permalink' => [ 'type' => 'string' ],
'focus_keyword' => [ 'type' => 'string' ],
'body' => [ 'type' => 'string' ],
'word_count' => [ 'type' => 'integer' ],
'excerpt_10pct' => [
'type' => 'string',
'description' => 'First 10% of the content body, used by the keywordIn10Percent test.',
],
'headings' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'level' => [ 'type' => 'string' ],
'text' => [ 'type' => 'string' ],
],
],
],
'images' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'alt' => [ 'type' => 'string' ],
],
],
],
'links' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'url' => [ 'type' => 'string' ],
'external' => [ 'type' => 'boolean' ],
],
],
],
],
],
'kb_link' => [
'type' => 'string',
'description' => 'KB article covering all 24 on-page SEO tests and how each is scored.',
],
'instructions' => [
'type' => 'string',
'description' => 'Guidance for the calling agent on how to use tests_to_run, content, and kb_link to produce a per-test analysis.',
],
'error' => [
'type' => [ 'object', 'null' ],
'properties' => [
'code' => [ 'type' => 'string' ],
'message' => [ 'type' => 'string' ],
],
],
],
];
}
}
@@ -0,0 +1,199 @@
<?php
/**
* Gathers raw content facts for the rank-math/analyze-post-content ability.
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Content_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Content_Analysis;
use WP_Post;
use RankMath\Helper;
use RankMath\Helpers\Str;
use RankMath\Helpers\Url;
use RankMath\Traits\Hooker;
defined( 'ABSPATH' ) || exit;
/**
* Builds the raw content payload an AI agent needs to evaluate the on-page SEO tests itself.
*
* This class does NOT score or judge anything — the actual test logic (Analyzer/Paper/Researcher)
* only exists client-side in JS and has no PHP port. Instead, it assembles the same facts the JS
* engine reads off the `Paper` object, so the calling agent can run the per-test evaluation.
*/
class Content_Analysis_Data {
use Hooker;
/**
* Canonical on-page test IDs for a post, mirroring Post_Screen::get_analysis().
*
* @var array
*/
const DEFAULT_TESTS = [
'contentHasTOC' => true,
'contentHasShortParagraphs' => true,
'contentHasAssets' => true,
'keywordInTitle' => true,
'keywordInMetaDescription' => true,
'keywordInPermalink' => true,
'keywordIn10Percent' => true,
'keywordInContent' => true,
'keywordInSubheadings' => true,
'keywordInImageAlt' => true,
'keywordDensity' => true,
'keywordNotUsed' => true,
'lengthContent' => true,
'lengthPermalink' => true,
'linksHasInternal' => true,
'linksHasExternals' => true,
'linksNotAllExternals' => true,
'titleStartWithKeyword' => true,
'titleSentiment' => true,
'titleHasPowerWords' => true,
'titleHasNumber' => true,
'hasContentAI' => true,
];
/**
* Build the content analysis payload for a post.
*
* @param WP_Post $post Post to analyze.
* @param string $keyword Optional focus keyword override.
* @return array
*/
public function get( WP_Post $post, string $keyword = '' ): array {
$post_id = $post->ID;
$body = $this->get_plain_text( $post->post_content );
$first_tenth = (int) ceil( mb_strlen( $body ) * 0.1 );
$title = Helper::get_post_meta( 'title', $post_id );
$description = Helper::get_post_meta( 'description', $post_id );
return [
'tests_to_run' => array_keys( $this->get_tests( $post->post_type ) ),
'content' => [
'title' => ! empty( $title ) ? $title : get_the_title( $post_id ),
'description' => ! empty( $description ) ? $description : '',
'permalink' => str_replace( home_url(), '', (string) get_permalink( $post_id ) ),
'focus_keyword' => '' !== $keyword ? $keyword : $this->get_primary_keyword( $post_id ),
'body' => $body,
'word_count' => str_word_count( $body ),
'excerpt_10pct' => Str::substr( $body, 0, $first_tenth ),
'headings' => $this->get_headings( $post->post_content ),
'images' => $this->get_images( $post->post_content ),
'links' => $this->get_links( $post->post_content ),
],
];
}
/**
* Get the on-page test IDs registered for a post type.
*
* @param string $post_type Post type slug.
* @return array
*/
private function get_tests( string $post_type ): array {
return $this->do_filter( 'researches/tests', self::DEFAULT_TESTS, $post_type );
}
/**
* Strip a post's content down to plain text.
*
* @param string $content Raw post content (may contain blocks/shortcodes/HTML).
* @return string
*/
private function get_plain_text( string $content ): string {
$content = strip_shortcodes( $content );
$content = wp_strip_all_tags( $content );
return trim( preg_replace( '/\s+/', ' ', $content ) );
}
/**
* Extract heading text grouped by level (H1-H6).
*
* @param string $content Raw post content.
* @return array
*/
private function get_headings( string $content ): array {
$headings = [];
if ( ! preg_match_all( '/<h([1-6])[^>]*>(.*?)<\/h\1>/is', $content, $matches, PREG_SET_ORDER ) ) {
return $headings;
}
foreach ( $matches as $match ) {
$headings[] = [
'level' => 'h' . $match[1],
'text' => trim( wp_strip_all_tags( $match[2] ) ),
];
}
return $headings;
}
/**
* Extract image alt text from post content.
*
* @param string $content Raw post content.
* @return array
*/
private function get_images( string $content ): array {
$images = [];
if ( ! preg_match_all( '/<img[^>]+>/i', $content, $matches ) ) {
return $images;
}
foreach ( $matches[0] as $tag ) {
$alt = preg_match( '/alt=["\']([^"\']*)["\']/i', $tag, $alt_match ) ? $alt_match[1] : '';
$images[] = [ 'alt' => $alt ];
}
return $images;
}
/**
* Extract links from post content, classified as internal or external.
*
* @param string $content Raw post content.
* @return array
*/
private function get_links( string $content ): array {
$links = [];
if ( ! preg_match_all( '/<a\s[^>]*href=["\']([^"\']+)["\'][^>]*>/i', $content, $matches ) ) {
return $links;
}
foreach ( $matches[1] as $href ) {
if ( Str::starts_with( '#', $href ) ) {
continue;
}
$links[] = [
'url' => $href,
'external' => Url::is_external( $href ),
];
}
return $links;
}
/**
* Get the primary focus keyword for the post.
*
* @param int $post_id Post ID.
* @return string
*/
private function get_primary_keyword( int $post_id ): string {
$keywords = get_post_meta( $post_id, 'rank_math_focus_keyword', true );
if ( empty( $keywords ) ) {
return '';
}
$parts = explode( ',', $keywords );
return trim( $parts[0] );
}
}
@@ -0,0 +1,359 @@
<?php
/**
* Ability: rank-math/get-seo-scores
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Content_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Content_Analysis;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-seo-scores ability.
*/
class Get_SEO_Scores implements Ability_Interface {
/**
* Default number of posts to return.
*/
const DEFAULT_NUMBER_OF_POSTS = 10;
/**
* Maximum number of posts to return.
*/
const MAX_NUMBER_OF_POSTS = 100;
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-seo-scores',
[
'category' => $this->category,
'label' => esc_html__( 'Get SEO scores', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns SEO scores and grades for posts. Before running, ask the user which posts they want to review: posts needing improvement (bad score), posts with no focus keyword, unscored posts, or simply the most recently modified posts. Use this to surface which posts need SEO attention without needing to know post IDs in advance.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'number_of_posts' => [
'type' => 'integer',
'description' => esc_html__( 'Number of recently modified posts to retrieve. Defaults to 10, maximum 100.', 'seo-by-rank-math' ),
'minimum' => 1,
'maximum' => self::MAX_NUMBER_OF_POSTS,
'default' => self::DEFAULT_NUMBER_OF_POSTS,
],
'post_type' => [
'type' => 'string',
'description' => esc_html__( 'Post type to filter by (e.g. "post", "page"). Defaults to all public post types.', 'seo-by-rank-math' ),
],
'seo_filter' => [
'type' => 'string',
'description' => esc_html__( 'Ask the user which posts they want to review before running this ability. Available options: "bad" (score ≤ 50, needs improvement), "good" (score 51–80, ok), "great" (score > 80), "empty-fk" (no focus keyword set), "unscored" (never analyzed). If the user does not specify, omit this parameter to return the most recently modified posts.', 'seo-by-rank-math' ),
'enum' => [ 'bad', 'good', 'great', 'empty-fk', 'unscored' ],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_onpage_analysis' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$limit = min( self::MAX_NUMBER_OF_POSTS, max( 1, absint( $input['number_of_posts'] ?? self::DEFAULT_NUMBER_OF_POSTS ) ) );
$post_type = isset( $input['post_type'] ) ? sanitize_key( $input['post_type'] ) : '';
$seo_filter = isset( $input['seo_filter'] ) ? sanitize_key( $input['seo_filter'] ) : '';
$meta_query = $this->build_meta_query( $seo_filter );
$query_args = [
'post_status' => 'publish',
'posts_per_page' => $limit,
'orderby' => 'modified',
'order' => 'DESC',
'fields' => 'ids',
];
if ( ! empty( $meta_query ) ) {
$query_args['meta_query'] = $meta_query;
// Order by score ascending for score-based filters so worst offenders surface first.
if ( in_array( $seo_filter, [ 'bad', 'good', 'great' ], true ) ) {
$query_args['orderby'] = 'meta_value_num';
$query_args['meta_key'] = 'rank_math_seo_score';
$query_args['order'] = 'ASC';
}
}
if ( ! empty( $post_type ) ) {
$query_args['post_type'] = $post_type;
} else {
$post_types = get_post_types( [ 'public' => true ] );
unset( $post_types['attachment'] );
$query_args['post_type'] = array_values( $post_types );
}
$post_ids = get_posts( $query_args );
$results = [];
foreach ( $post_ids as $post_id ) {
$results[] = $this->build_score_result( $post_id );
}
rank_math()->tracking->track_ability_executed(
'SEO Scores Retrieved',
[
'count' => count( $results ),
'post_type' => ! empty( $post_type ) ? $post_type : 'all',
'seo_filter' => ! empty( $seo_filter ) ? $seo_filter : 'none',
],
'rank_math_onpage_analysis'
);
return $results;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'post_id' => [ 'type' => 'integer' ],
'title' => [ 'type' => 'string' ],
'keyword' => [
'type' => [ 'string', 'null' ],
'description' => 'Primary focus keyword, or null if not set.',
],
'score' => [
'type' => [ 'integer', 'null' ],
'minimum' => 0,
'maximum' => 100,
],
'grade' => [
'type' => 'string',
'enum' => [ 'good', 'ok', 'bad', 'na' ],
],
'label' => [
'type' => 'string',
'description' => 'Human-readable grade label.',
],
'last_updated' => [ 'type' => 'integer' ],
],
],
];
}
/**
* Build the meta query for a given SEO filter.
*
* Mirrors the filter conditions defined in Post_Filters::set_seo_filters().
*
* @param string $filter SEO filter slug.
* @return array
*/
private function build_meta_query( string $filter ): array {
$hash = [
'empty-fk' => [
'key' => 'rank_math_focus_keyword',
'compare' => 'NOT EXISTS',
],
'unscored' => [
'key' => 'rank_math_seo_score',
'compare' => 'NOT EXISTS',
],
'bad' => [
'key' => 'rank_math_seo_score',
'value' => 50,
'compare' => '<=',
'type' => 'numeric',
],
'good' => [
'key' => 'rank_math_seo_score',
'value' => [ 51, 80 ],
'compare' => 'BETWEEN',
'type' => 'numeric',
],
'great' => [
'key' => 'rank_math_seo_score',
'value' => 80,
'compare' => '>',
'type' => 'numeric',
],
];
if ( ! isset( $hash[ $filter ] ) ) {
return [];
}
$meta_query = [];
// Score-based filters exclude noindexed posts and require a focus keyword, matching Post_Filters behaviour.
if ( in_array( $filter, [ 'bad', 'good', 'great' ], true ) ) {
$meta_query['relation'] = 'AND';
$meta_query[] = [
'relation' => 'OR',
[
'key' => 'rank_math_robots',
'value' => 'noindex',
'compare' => 'NOT LIKE',
],
[
'key' => 'rank_math_robots',
'compare' => 'NOT EXISTS',
],
];
$meta_query[] = [
'key' => 'rank_math_focus_keyword',
'compare' => 'EXISTS',
];
$meta_query[] = [
'key' => 'rank_math_focus_keyword',
'value' => '',
'compare' => '!=',
];
}
$meta_query[] = $hash[ $filter ];
return $meta_query;
}
/**
* Build the score result array for a single post.
*
* @param int $post_id Post ID.
* @return array
*/
private function build_score_result( int $post_id ): array {
$raw_score = get_post_meta( $post_id, 'rank_math_seo_score', true );
$keyword = $this->get_primary_keyword( $post_id );
if ( '' === $raw_score || false === $raw_score ) {
return [
'post_id' => $post_id,
'title' => get_the_title( $post_id ),
'keyword' => ! empty( $keyword ) ? $keyword : null,
'score' => null,
'grade' => 'na',
'label' => esc_html__( 'Not available', 'seo-by-rank-math' ),
'last_updated' => (int) get_post_modified_time( 'U', true, $post_id ),
];
}
$score = absint( $raw_score );
$grade = $score >= 80 ? 'good' : ( $score >= 50 ? 'ok' : 'bad' );
$label = $this->grade_to_label( $grade );
return [
'post_id' => $post_id,
'title' => get_the_title( $post_id ),
'keyword' => ! empty( $keyword ) ? $keyword : null,
'score' => $score,
'grade' => $grade,
'label' => $label,
'last_updated' => (int) get_post_modified_time( 'U', true, $post_id ),
];
}
/**
* Convert a grade slug to a human-readable label.
*
* @param string $grade Grade slug.
* @return string
*/
private function grade_to_label( string $grade ): string {
$labels = [
'good' => esc_html__( 'Good', 'seo-by-rank-math' ),
'ok' => esc_html__( 'OK', 'seo-by-rank-math' ),
'bad' => esc_html__( 'Needs improvement', 'seo-by-rank-math' ),
];
return $labels[ $grade ] ?? esc_html__( 'Not available', 'seo-by-rank-math' );
}
/**
* Get the primary focus keyword for a post.
*
* @param int $post_id Post ID.
* @return string
*/
private function get_primary_keyword( int $post_id ): string {
$keywords = get_post_meta( $post_id, 'rank_math_focus_keyword', true );
if ( empty( $keywords ) ) {
return '';
}
$parts = explode( ',', $keywords );
return trim( $parts[0] );
}
}
@@ -0,0 +1,89 @@
<?php
/**
* Subscriber for Content Analysis abilities.
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Content_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Content_Analysis;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Content Analysis ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Content Analysis abilities.
*/
const CATEGORY_SLUG = 'rank-math-content-analysis';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_seo_scores' );
$this->action( 'wp_abilities_api_init', 'register_analyze_post_content' );
}
/**
* Register the Content Analysis ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Content Analysis', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to retrieve on-page SEO analysis scores for posts.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-seo-scores ability.
*
* @return void
*/
public function register_get_seo_scores(): void {
( new Get_SEO_Scores( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/analyze-post-content ability.
*
* @return void
*/
public function register_analyze_post_content(): void {
( new Analyze_Post_Content( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1,2 @@
<?php
// Silence is golden.
@@ -0,0 +1,41 @@
<?php
/**
* Interface for Rank Math abilities.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities;
defined( 'ABSPATH' ) || exit;
/**
* Ability interface.
*/
interface Ability_Interface {
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void;
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool;
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array;
}
@@ -0,0 +1,26 @@
<?php
/**
* Interface for Rank Math ability subscribers.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities;
defined( 'ABSPATH' ) || exit;
/**
* Subscriber interface.
*/
interface Subscriber_Interface {
/**
* Register the subscriber's category and abilities with WordPress hooks.
*
* @return void
*/
public function register(): void;
}
@@ -0,0 +1,207 @@
<?php
/**
* Ability: rank-math/get-link-report
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-link-report ability.
*/
class Get_Link_Report implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Runner instance.
*
* @var Link_Report_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Link_Report_Runner|null $runner Runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Link_Report_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Link_Report_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-link-report',
[
'category' => $this->category,
'label' => \esc_html__( 'Get link report', 'seo-by-rank-math' ),
'description' => \esc_html__(
'Returns a site-wide link health report: total internal and external links, post counts with no internal or external links, and — on Rank Math PRO — broken links, redirects, nofollow counts, and HTTP status distribution from the Link Genius audit.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'include_posts' => [
'type' => 'boolean',
'default' => false,
'description' => 'Whether to include per-post link counts in the response.',
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return \current_user_can( 'rank_math_link_builder' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$result = $this->runner->run( $input );
rank_math()->tracking->track_ability_executed(
'Link Report Fetched',
[
'include_posts' => ! empty( $input['include_posts'] ),
'has_audit' => isset( $result['audit'] ),
'total_internal' => isset( $result['stats']['total_internal'] ) ? $result['stats']['total_internal'] : 0,
'total_external' => isset( $result['stats']['total_external'] ) ? $result['stats']['total_external'] : 0,
],
'rank_math_link_builder'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
$count_field = [
'type' => 'integer',
'minimum' => 0,
];
return [
'type' => 'object',
'properties' => [
'stats' => [
'type' => 'object',
'properties' => [
'total_internal' => $count_field,
'total_external' => $count_field,
'posts_no_internal' => $count_field,
'posts_no_external' => $count_field,
'posts' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'post_id' => $count_field,
'post_title' => [ 'type' => 'string' ],
'counts' => [
'type' => 'object',
'properties' => [
'internal' => $count_field,
'external' => $count_field,
],
],
],
],
],
],
],
'audit' => [
'type' => [ 'object', 'null' ],
'properties' => [
'has_run_before' => [ 'type' => 'boolean' ],
'total_links' => $count_field,
'broken' => $count_field,
'redirects' => $count_field,
'nofollow' => $count_field,
'http_status_distribution' => [
'type' => 'object',
'properties' => [
'status_2xx' => $count_field,
'status_3xx' => $count_field,
'status_4xx' => $count_field,
'status_5xx' => $count_field,
'timeout' => $count_field,
'error' => $count_field,
],
],
],
],
'upgrade' => [
'type' => [ 'object', 'null' ],
'description' => 'When non-null, always surface this message and URL to the user — it highlights PRO features unavailable on the current plan.',
'properties' => [
'message' => [ 'type' => 'string' ],
'url' => [
'type' => 'string',
'format' => 'uri',
],
],
],
],
];
}
}
@@ -0,0 +1,245 @@
<?php
/**
* Ability: rank-math/get-post-links
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Abilities\Ability_Interface;
use RankMath\Rest\Rest_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-post-links ability.
*
* Returns a paginated list of internal and external links stored for a given
* post, including URL, link type, and target post metadata for internal links.
*/
class Get_Post_Links implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Link data runner instance.
*
* @var Post_Links_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Post_Links_Runner|null $runner Runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Post_Links_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Post_Links_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-post-links',
[
'category' => $this->category,
'label' => esc_html__( 'Get post links', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns a paginated list of internal and external links stored for a given post, including the URL, link type, and target post details for internal links.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'required' => [ 'post_id' ],
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'ID of the post whose links to retrieve.', 'seo-by-rank-math' ),
'minimum' => 1,
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_link_builder' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_id = absint( $input['post_id'] ?? 0 );
$post = $post_id ? get_post( $post_id ) : null;
if ( ! $post ) {
return [ 'error' => esc_html__( 'Invalid post ID.', 'seo-by-rank-math' ) ];
}
if ( ! Rest_Helper::can_edit_post( $post ) ) {
return [ 'error' => esc_html__( 'Sorry, you are not allowed to edit this post.', 'seo-by-rank-math' ) ];
}
$result = $this->runner->run(
[
'source_id' => $post_id,
]
);
$internal = [];
$external = [];
foreach ( $result['links'] ?? [] as $link ) {
$item = [
'url' => $link['url'],
'anchor' => $link['anchor'],
'dofollow' => $link['dofollow'],
];
if ( 'internal' === $link['type'] ) {
$item['target_post_id'] = $link['target_post_id'];
$internal[] = $item;
} else {
$external[] = $item;
}
}
$output = [
'post_id' => $post_id,
'internal' => $internal,
'external' => $external,
'counts' => [
'internal' => count( $internal ),
'external' => count( $external ),
],
];
rank_math()->tracking->track_ability_executed(
'Post Links Fetched',
[
'post_id' => $post_id,
'internal' => count( $internal ),
'external' => count( $external ),
],
'rank_math_link_builder'
);
return $output;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
$link_item = [
'type' => 'object',
'properties' => [
'url' => [
'type' => 'string',
'description' => 'Full URL of the link.',
],
'anchor' => [
'type' => [ 'string', 'null' ],
'description' => 'Anchor text of the link. Null when anchor data is unavailable (FREE plugin).',
],
'dofollow' => [
'type' => [ 'boolean', 'null' ],
'description' => 'True when the link is dofollow. Null when rel data is unavailable.',
],
],
];
$internal_item = $link_item;
$internal_item['properties']['target_post_id'] = [
'type' => 'integer',
'description' => 'WordPress post ID of the link target.',
];
return [
'type' => 'object',
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => 'WordPress post ID of the source post.',
],
'internal' => [
'type' => 'array',
'description' => 'Internal links found in the post.',
'items' => $internal_item,
],
'external' => [
'type' => 'array',
'description' => 'External links found in the post.',
'items' => $link_item,
],
'counts' => [
'type' => 'object',
'description' => 'Count of links returned per type.',
'properties' => [
'internal' => [
'type' => 'integer',
'description' => 'Number of internal links returned.',
],
'external' => [
'type' => 'integer',
'description' => 'Number of external links returned.',
],
],
],
'error' => [
'type' => 'string',
],
],
];
}
}
@@ -0,0 +1,91 @@
<?php
/**
* Runner for the get-link-report ability.
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Links\Api\Controller;
defined( 'ABSPATH' ) || exit;
/**
* Calls the existing Links REST controller methods to build a link report.
*/
class Link_Report_Runner {
/**
* Links REST controller.
*
* @var Controller
*/
private $controller;
/**
* Constructor.
*
* @param Controller|null $controller Links REST controller.
*/
public function __construct( ?Controller $controller = null ) {
$this->controller = $controller ?? new Controller();
}
/**
* Build and return the link report.
*
* @param array $input Ability input (e.g. include_posts).
* @return array
*/
public function run( array $input = [] ): array {
$posts_response = $this->controller->get_posts_stats();
$links_response = $this->controller->get_links_stats();
$posts = (array) $posts_response->get_data();
$links = (array) $links_response->get_data();
$total_posts = (int) ( $posts['total_posts'] ?? 0 );
$result = [
'stats' => [
'total_internal' => (int) ( $links['internal'] ?? 0 ),
'total_external' => (int) ( $links['external'] ?? 0 ),
'posts_no_internal' => $total_posts - (int) ( $posts['posts_with_internal'] ?? 0 ),
'posts_no_external' => $total_posts - (int) ( $posts['posts_with_external'] ?? 0 ),
],
];
if ( ! empty( $input['include_posts'] ) ) {
$data = $this->controller->get_posts_data( [ 'per_page' => 100 ] );
$result['stats']['posts'] = array_map(
function ( $post ) {
$row = (array) $post;
return [
'post_id' => (int) ( $row['post_id'] ?? 0 ),
'post_title' => (string) ( $row['post_title'] ?? '' ),
'counts' => [
'internal' => (int) ( $row['internal_link_count'] ?? 0 ),
'external' => (int) ( $row['external_link_count'] ?? 0 ),
],
];
},
$data['posts']
);
}
$result = (array) apply_filters( 'rank_math/abilities/link_report_result', $result, $input );
if ( ! isset( $result['audit'] ) ) {
$result['upgrade'] = [
'message' => \esc_html__( 'Upgrade to Rank Math PRO to unlock broken link detection, redirect chain analysis, and HTTP status distribution from the AI Link Genius audit.', 'seo-by-rank-math' ),
'url' => 'https://rankmath.com/pricing/',
];
}
return $result;
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Runner: fetches per-post link data via the existing links REST endpoint.
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Links\Api\Controller;
defined( 'ABSPATH' ) || exit;
/**
* Delegates to the Links REST controller to retrieve individual link rows for a post.
*
* Calls Controller::get_links() directly instead of going through the REST stack
* so that the request stays in-process. PRO plugin overrides
* (rank_math/links/rest_links_response) still apply because they live inside
* the controller callback itself.
*/
class Post_Links_Runner {
/**
* Links REST controller.
*
* @var Controller
*/
private $controller;
/**
* Constructor.
*
* @param Controller|null $controller Links REST controller (injectable for tests).
*/
public function __construct( ?Controller $controller = null ) {
$this->controller = $controller ?? new Controller();
}
/**
* Fetch link rows for a post by calling the links controller directly.
*
* @param array $args {
* Query arguments.
*
* @type int $post_id Source post ID. Must be > 0.
* @type int $page 1-based page number.
* @type int $per_page Rows per page (max 100).
* @type string $is_internal Filter value: '1' = internal only, '0' = external only, '' = all.
* }
* @return array { links: array, total: int, pages: int }
*/
public function run( array $args ): array {
$data = $this->controller->get_links_data( $args );
$links = [];
foreach ( $data['links'] ?? [] as $link ) {
$links[] = [
'id' => (int) $link->id,
'url' => $link->url,
'type' => $link->type,
'anchor' => (string) ( $link->anchor_text ?? '' ),
'dofollow' => isset( $link->is_nofollow ) ? ! (bool) $link->is_nofollow : null,
'target_post_id' => (int) ( $link->target_post_id ?? 0 ),
'target_title' => $link->target_title ?? '',
'target_url' => $link->target_url ?? '',
];
}
return [
'links' => $links,
'total' => (int) ( $data['total'] ?? 0 ),
'pages' => (int) ( $data['pages'] ?? 0 ),
];
}
}
@@ -0,0 +1,89 @@
<?php
/**
* Subscriber for Link Genius abilities.
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Link Genius ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Link Genius abilities.
*/
const CATEGORY_SLUG = 'rank-math-link-genius';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_link_report' );
$this->action( 'wp_abilities_api_init', 'register_get_post_links' );
}
/**
* Register the Link Genius ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'AI Link Genius', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to retrieve and analyse internal and external link data for posts.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-link-report ability.
*
* @return void
*/
public function register_get_link_report(): void {
( new Get_Link_Report( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/get-post-links ability.
*
* @return void
*/
public function register_get_post_links(): void {
( new Get_Post_Links( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,219 @@
<?php
/**
* Ability: rank-math/get-404-logs
*
* @since 1.0.279
* @package RankMath
* @subpackage RankMath\Abilities\Monitor_404
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Monitor_404;
use RankMath\Abilities\Ability_Interface;
use RankMath\Monitor\DB;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-404-logs ability.
*/
class Get_404_Logs implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-404-logs',
[
'category' => $this->category,
'label' => esc_html__( 'Get 404 logs', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the 404 error monitor log entries, with hit counts and referer/user-agent data.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'per_page' => [
'type' => 'integer',
'description' => esc_html__( 'The number of log entries to return per page.', 'seo-by-rank-math' ),
'default' => 100,
'minimum' => 1,
'maximum' => 1000,
],
'page' => [
'type' => 'integer',
'description' => esc_html__( 'The page number to return.', 'seo-by-rank-math' ),
'default' => 1,
],
'orderby' => [
'type' => 'string',
'enum' => [ 'hits', 'accessed' ],
'default' => 'hits',
'description' => esc_html__( 'Field to order results by.', 'seo-by-rank-math' ),
],
'order' => [
'type' => 'string',
'enum' => [ 'asc', 'desc' ],
'default' => 'desc',
'description' => esc_html__( 'Sort direction.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_404_monitor' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$per_page = isset( $input['per_page'] ) ? absint( $input['per_page'] ) : 100;
$page = max( 1, isset( $input['page'] ) ? (int) $input['page'] : 1 );
$orderby = isset( $input['orderby'] ) ? sanitize_text_field( $input['orderby'] ) : 'hits';
$order = isset( $input['order'] ) && in_array( $input['order'], [ 'asc', 'desc' ], true ) ? $input['order'] : 'desc';
$order_map = [
'hits' => 'times_accessed',
'accessed' => 'accessed',
];
$logs = DB::get_logs(
[
'orderby' => $order_map[ $orderby ] ?? 'times_accessed',
'order' => strtoupper( $order ),
'limit' => $per_page,
'paged' => $page,
]
);
$items = array_map(
function ( $log ) {
return [
'id' => (int) $log['id'],
'uri' => $log['uri'],
'hits' => (int) $log['times_accessed'],
'referer' => $log['referer'],
'user_agent' => $log['user_agent'],
'accessed' => $log['accessed'],
];
},
$logs['logs']
);
$stats = DB::get_stats();
$result = [
'stats' => [
'total_urls' => (int) ( $stats->total ?? 0 ),
'total_hits' => (int) ( $stats->hits ?? 0 ),
],
'total' => (int) $logs['count'],
'items' => $items,
];
rank_math()->tracking->track_ability_executed(
'404 Logs Fetched',
[ 'count' => (int) $logs['count'] ],
'rank_math_404_monitor'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'stats' => [
'type' => 'object',
'description' => esc_html__( 'Log counts across the entire table, independent of pagination.', 'seo-by-rank-math' ),
'properties' => [
'total_urls' => [ 'type' => 'integer' ],
'total_hits' => [ 'type' => 'integer' ],
],
],
'total' => [
'type' => 'integer',
'description' => esc_html__( 'Number of log entries included in this response (the size of items).', 'seo-by-rank-math' ),
],
'items' => [
'type' => 'array',
'description' => esc_html__( 'The 404 log entries for the requested page.', 'seo-by-rank-math' ),
'items' => [
'type' => 'object',
'properties' => [
'id' => [ 'type' => 'integer' ],
'uri' => [ 'type' => 'string' ],
'hits' => [ 'type' => 'integer' ],
'referer' => [ 'type' => 'string' ],
'user_agent' => [ 'type' => 'string' ],
'accessed' => [ 'type' => 'string' ],
],
],
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for 404 Monitor abilities.
*
* @since 1.0.279
* @package RankMath
* @subpackage RankMath\Abilities\Monitor_404
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Monitor_404;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the 404 Monitor ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for 404 Monitor abilities.
*/
const CATEGORY_SLUG = 'rank-math-404-monitor';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_404_logs' );
}
/**
* Register the 404 Monitor ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( '404 Monitor', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to inspect the 404 error monitor log.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-404-logs ability.
*
* @return void
*/
public function register_get_404_logs(): void {
( new Get_404_Logs( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,178 @@
<?php
/**
* Ability: rank-math/get-post-seo-meta
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Post_SEO
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Post_SEO;
use RankMath\Abilities\Ability_Interface;
use RankMath\Paper\Singular;
use RankMath\Rest\Rest_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-post-seo-meta ability.
*/
class Get_Post_SEO_Meta implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-post-seo-meta',
[
'category' => $this->category,
'label' => esc_html__( 'Get post SEO metadata', 'seo-by-rank-math' ),
'description' => esc_html__( 'Returns the full SEO metadata for a post: title, description, focus keyword, robots settings, canonical URL, Open Graph and Twitter overrides, and the current SEO score.', 'seo-by-rank-math' ),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'post_id' ],
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'The ID of the post to retrieve SEO metadata for.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_onpage_general' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_id = absint( $input['post_id'] );
$post = get_post( $post_id );
if ( ! $post || ! in_array( get_post_status( $post ), [ 'publish', 'draft', 'private', 'pending', 'future' ], true ) ) {
return [ 'error' => esc_html__( 'No post found with the given ID, or the post status is not supported.', 'seo-by-rank-math' ) ];
}
if ( ! Rest_Helper::can_edit_post( $post ) ) {
return [ 'error' => esc_html__( 'Sorry, you are not allowed to edit this post.', 'seo-by-rank-math' ) ];
}
$result = ( new Singular() )->get_seo_meta( $post_id );
if ( empty( $result['error'] ) ) {
rank_math()->tracking->track_ability_executed(
'Post SEO Meta Fetched',
[ 'post_id' => $post_id ],
'rank_math_onpage_general'
);
}
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'post_id' => [
'type' => 'integer',
],
'title' => [
'type' => 'string',
],
'description' => [
'type' => 'string',
],
'focus_keyword' => [
'type' => 'string',
],
'robots' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
],
'canonical' => [
'type' => 'string',
],
'og_title' => [
'type' => 'string',
],
'og_description' => [
'type' => 'string',
],
'twitter_title' => [
'type' => 'string',
],
'twitter_description' => [
'type' => 'string',
],
'seo_score' => [
'type' => 'integer',
'minimum' => 0,
'maximum' => 100,
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Post SEO abilities.
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Post_SEO
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Post_SEO;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Post SEO ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Post SEO abilities.
*/
const CATEGORY_SLUG = 'rank-math-post-seo';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_post_seo_meta' );
}
/**
* Register the Post SEO ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Post SEO', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to read and manage per-post SEO metadata.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-post-seo-meta ability.
*
* @return void
*/
public function register_get_post_seo_meta(): void {
( new Get_Post_SEO_Meta( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,233 @@
<?php
/**
* Ability: rank-math/get-redirections
*
* @since 1.0.278
* @package RankMath
* @subpackage RankMath\Abilities\Redirections
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Redirections;
use RankMath\Abilities\Ability_Interface;
use RankMath\Helper;
use RankMath\Redirections\DB;
use RankMath\Admin\Database\Database;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-redirections ability.
*/
class Get_Redirections implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-redirections',
[
'category' => $this->category,
'label' => esc_html__( 'Get redirections', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the redirections for a site.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'status' => [
'type' => 'string',
'enum' => [ 'active', 'inactive', 'all' ],
'default' => 'all',
'description' => esc_html__( 'Filter redirections by status.', 'seo-by-rank-math' ),
],
'per_page' => [
'type' => 'integer',
'description' => esc_html__( 'The number of redirections to return per page.', 'seo-by-rank-math' ),
'default' => 100,
'minimum' => 1,
'maximum' => 1000,
],
'page' => [
'type' => 'integer',
'description' => esc_html__( 'The page number to return.', 'seo-by-rank-math' ),
'default' => 1,
],
'search' => [
'type' => 'string',
'description' => esc_html__( 'Search redirections by source or target URL.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return Helper::has_cap( 'redirections' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$search = isset( $input['search'] ) ? sanitize_text_field( $input['search'] ) : '';
$status = isset( $input['status'] ) ? sanitize_text_field( $input['status'] ) : 'all';
$per_page = isset( $input['per_page'] ) ? absint( $input['per_page'] ) : 100;
$page = isset( $input['page'] ) ? absint( $input['page'] ) : 1;
$redirections = DB::get_redirections(
[
'limit' => $per_page,
'paged' => $page,
'search' => $search,
'status' => $status,
]
);
$items = array_map(
function ( $item ) {
$item['sources'] = maybe_unserialize( $item['sources'] );
return $item;
},
$redirections['redirections']
);
$counts = DB::get_counts();
$result = [
'stats' => [
'total' => absint( $counts['all'] ),
'active' => absint( $counts['active'] ),
'inactive' => absint( $counts['inactive'] ),
'by_type' => DB::get_counts_by_type(),
],
'total' => count( $items ),
'page' => $page,
'per_page' => $per_page,
'items' => $items,
];
rank_math()->tracking->track_ability_executed(
'Redirections Fetched',
[
'count' => $redirections['count'],
'status_filter' => $status,
],
'rank_math_redirections'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'stats' => [
'type' => 'object',
'description' => esc_html__( 'Redirection counts across all statuses, independent of the status filter applied to items.', 'seo-by-rank-math' ),
'properties' => [
'total' => [ 'type' => 'integer' ],
'active' => [ 'type' => 'integer' ],
'inactive' => [ 'type' => 'integer' ],
'by_type' => [
'type' => 'object',
'description' => esc_html__( 'Non-trashed redirection counts grouped by HTTP redirect type (header code), e.g. { "301": 12, "302": 4 }.', 'seo-by-rank-math' ),
'additionalProperties' => [ 'type' => 'integer' ],
],
],
],
'total' => [
'type' => 'integer',
'description' => esc_html__( 'Number of redirections included in this response (the size of items).', 'seo-by-rank-math' ),
],
'page' => [
'type' => 'integer',
],
'per_page' => [
'type' => 'integer',
],
'items' => [
'type' => 'array',
'description' => esc_html__( 'The redirections for the requested page.', 'seo-by-rank-math' ),
'items' => [
'type' => 'object',
'properties' => [
'id' => [ 'type' => 'integer' ],
'sources' => [ 'type' => 'array' ],
'url_to' => [ 'type' => 'string' ],
'header_code' => [ 'type' => 'integer' ],
'hits' => [ 'type' => 'integer' ],
'status' => [
'type' => 'string',
'enum' => [ 'active', 'inactive', 'trashed' ],
],
'created' => [ 'type' => 'string' ],
'updated' => [ 'type' => 'string' ],
'last_accessed' => [ 'type' => 'string' ],
],
],
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Redirection abilities.
*
* @since 1.0.278
* @package RankMath
* @subpackage RankMath\Abilities\Redirections
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Redirections;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Redirection ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Redirection abilities.
*/
const CATEGORY_SLUG = 'rank-math-redirections';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_redirections' );
}
/**
* Register the Redirection ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Redirections', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to read and manage redirections for a site.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-redirections ability.
*
* @return void
*/
public function register_get_redirections(): void {
( new Get_Redirections( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,221 @@
<?php
/**
* Ability: rank-math/get-post-schema
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Schema
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Schema;
use RankMath\Abilities\Ability_Interface;
use RankMath\Helper;
use RankMath\Rest\Rest_Helper;
use RankMath\Schema\DB;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-post-schema ability.
*/
class Get_Post_Schema implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-post-schema',
[
'category' => $this->category,
'label' => esc_html__( 'Get post schema', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the schema markup attached to a post and the schema types available on this install. Use this after rank-math/get-post-seo-meta to check what schema is already set and what types are supported before making a recommendation. If the schema type you want to recommend is not in available_types.types and upgrade_message is present, show upgrade_message verbatim to the user and do not suggest adding the schema type directly.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'post_id' ],
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'The ID of the post to retrieve schema markup for.', 'seo-by-rank-math' ),
],
'include_available_types' => [
'type' => 'boolean',
'description' => esc_html__( 'When true (default), includes the schema types available on this install. Always pass true when evaluating which schema to add.', 'seo-by-rank-math' ),
'default' => true,
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_onpage_snippet' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_id = absint( $input['post_id'] );
$include = (bool) ( $input['include_available_types'] ?? true );
$post = $post_id ? get_post( $post_id ) : null;
if ( ! $post ) {
return [ 'error' => esc_html__( 'Invalid post ID.', 'seo-by-rank-math' ) ];
}
if ( ! Rest_Helper::can_edit_post( $post ) ) {
return [ 'error' => esc_html__( 'Sorry, you are not allowed to edit this post.', 'seo-by-rank-math' ) ];
}
$schemas = DB::get_schemas( $post_id );
$types_raw = DB::get_schema_types( $post_id );
$schema_types = $types_raw
? array_values( array_filter( array_map( 'trim', explode( ',', $types_raw ) ) ) )
: [];
$result = [
'post_id' => $post_id,
'schema_types' => $schema_types,
'schemas' => array_values( $schemas ),
];
if ( $include ) {
$result['available_types'] = $this->build_available_types();
}
rank_math()->tracking->track_ability_executed(
'Post Schema Fetched',
[
'post_id' => $post_id,
'schema_count' => count( $schemas ),
'include_available_types' => $include,
],
'rank_math_onpage_snippet'
);
return $result;
}
/**
* Build the available_types catalog.
*
* `types` lists what is installable right now: FREE types always present, PRO named
* types added automatically when PRO is active via rank_math/settings/snippet/types filter.
* `upgrade_message` is only present when PRO is not active; it is a ready-made sentence
* the agent should surface verbatim when a needed schema type is not in `types`.
*
* @return array
*/
private function build_available_types(): array {
$available = [
'types' => array_keys( Helper::choices_rich_snippet_types() ),
];
if ( ! defined( 'RANK_MATH_PRO_VERSION' ) ) {
$available['upgrade_message'] = esc_html__(
'This schema type requires Rank Math PRO. Upgrade at rankmath.com/pro to unlock Movie, Dataset, Fact Check, and custom schema types.',
'seo-by-rank-math'
);
}
return $available;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'post_id' => [
'type' => 'integer',
],
'schema_types' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
],
'schemas' => [
'type' => 'array',
'items' => [ 'type' => 'object' ],
],
'available_types' => [
'type' => 'object',
'properties' => [
'types' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
'description' => 'Schema type keys available on this install. FREE types always present; PRO named types added when PRO is active.',
],
'upgrade_message' => [
'type' => 'string',
'description' => 'Only present when PRO is not active. Show this verbatim to the user when the recommended schema type is not in types.',
],
],
],
'error' => [
'type' => 'string',
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Schema abilities.
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Schema
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Schema;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Schema ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Schema abilities.
*/
const CATEGORY_SLUG = 'rank-math-schema';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_post_schema' );
}
/**
* Register the Schema ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Schema', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to read and manage schema markup attached to posts.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-post-schema ability.
*
* @return void
*/
public function register_get_post_schema(): void {
( new Get_Post_Schema( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,120 @@
<?php
/**
* Audit result value object for the rank-math/audit-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
defined( 'ABSPATH' ) || exit;
/**
* Site SEO audit result, agent-consumable shape.
*/
class Audit_Result {
/**
* Analyzed URL.
*
* @var string
*/
public $url;
/**
* Score 0–100.
*
* @var int
*/
public $score;
/**
* Grade: good|average|bad.
*
* @var string
*/
public $grade;
/**
* Outcome counts: ok, fail, warning, info.
*
* @var array
*/
public $statuses;
/**
* Total tests counted.
*
* @var int
*/
public $total_tests;
/**
* Unix timestamp of last run, 0 if never.
*
* @var int
*/
public $last_run_at;
/**
* Remote API status: ok|unavailable|skipped.
*
* @var string
*/
public $remote_api_status;
/**
* Per-test findings.
*
* @var Finding[]
*/
public $findings;
/**
* Error details when the audit could not run, or null on success.
* Shape: { code: string, message: string }
*
* @var array|null
*/
public $error;
/**
* Constructor.
*
* @param array $args See properties.
*/
public function __construct( array $args ) {
foreach ( $args as $key => $value ) {
if ( property_exists( $this, $key ) ) {
$this->{$key} = $value;
}
}
}
/**
* Serialize to array.
*
* @return array
*/
public function to_array() {
return [
'url' => $this->url,
'score' => (int) $this->score,
'grade' => $this->grade,
'statuses' => (array) $this->statuses,
'total_tests' => (int) $this->total_tests,
'last_run_at' => (int) $this->last_run_at,
'remote_api_status' => $this->remote_api_status,
'findings' => array_map(
function ( Finding $f ) {
return $f->to_array();
},
(array) $this->findings
),
'error' => $this->error,
];
}
}
@@ -0,0 +1,226 @@
<?php
/**
* Audit runner service for the rank-math/audit-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\KB;
use RankMath\Helpers\Url;
use RankMath\SEO_Analysis\SEO_Analyzer;
defined( 'ABSPATH' ) || exit;
/**
* Runs the Rank Math site SEO audit and shapes the result for ability/MCP consumers.
*/
class Audit_Runner {
/**
* SEO Analyzer instance.
*
* @var SEO_Analyzer
*/
private $analyzer;
/**
* Constructor.
*
* @param SEO_Analyzer|null $analyzer SEO Analyzer instance.
*/
public function __construct( ?SEO_Analyzer $analyzer = null ) {
$this->analyzer = $analyzer ?? new SEO_Analyzer();
}
/**
* Run the audit and return a structured result.
*
* External URL auditing requires Rank Math PRO. FREE installs receive
* an Audit_Result with error.code 'pro_required' instead of findings.
*
* @param bool $refresh Re-run tests instead of returning cached results.
* @param string|null $url Optional URL to audit. Defaults to this site's home URL.
* @return Audit_Result
*/
public function run( $refresh = true, $url = null ) {
if ( ! empty( $url ) ) {
$clean = wp_http_validate_url( $url );
if ( false === $clean ) {
return $this->error_result(
'invalid_url',
__( 'The provided URL is not valid.', 'seo-by-rank-math' )
);
}
if ( Url::is_external( $clean ) && ! apply_filters( 'rank_math/analysis/is_allowed_url', false, $clean ) ) {
return $this->error_result(
'pro_required',
sprintf(
/* translators: %s: URL to the Rank Math PRO upgrade page */
__( 'Competitor URL analysis requires Rank Math PRO. Upgrade at %s', 'seo-by-rank-math' ),
KB::get( 'pro', 'Audit Site SEO Ability' )
)
);
}
}
// The tests file is normally loaded only in the admin context. Include it here
// so local tests are available when the ability is invoked via REST/MCP.
$tests_file = RANK_MATH_PATH . 'includes/modules/seo-analysis/seo-analysis-tests.php';
if ( file_exists( $tests_file ) ) {
include_once $tests_file;
}
if ( ! empty( $url ) ) {
$this->analyzer->analyse_url = esc_url_raw( $url );
$this->analyzer->analyse_subpage = true;
}
$this->analyzer->set_url();
if ( $refresh || ! $this->has_cached_results() ) {
$this->analyzer->run_tests( $refresh );
} else {
$this->analyzer->get_results_from_storage();
}
return $this->shape( $this->analyzer );
}
/**
* Build a minimal Audit_Result carrying only an error (no findings).
*
* @param string $code Machine-readable error code.
* @param string $message Human-readable message for the AI/user.
* @return Audit_Result
*/
private function error_result( $code, $message ) {
return new Audit_Result(
[
'url' => '',
'score' => 0,
'grade' => 'bad',
'statuses' => [
'ok' => 0,
'fail' => 0,
'warning' => 0,
'info' => 0,
],
'total_tests' => 0,
'last_run_at' => 0,
'remote_api_status' => 'skipped',
'findings' => [],
'error' => [
'code' => $code,
'message' => $message,
],
]
);
}
/**
* Whether a cached audit result exists.
*
* @return bool
*/
private function has_cached_results() {
return (bool) get_option( 'rank_math_seo_analysis_results' );
}
/**
* Build an Audit_Result from a populated SEO_Analyzer.
*
* @param SEO_Analyzer $analyzer Populated analyzer instance.
* @return Audit_Result
*/
private function shape( SEO_Analyzer $analyzer ) {
$findings = [];
$statuses = [
'ok' => 0,
'fail' => 0,
'warning' => 0,
'info' => 0,
];
$total = 0;
$score_sum = 0;
$score_pass = 0;
if ( is_array( $analyzer->results ) ) {
foreach ( $analyzer->results as $id => $result ) {
if ( ! is_object( $result ) || $result->is_hidden() || $result->is_excluded() ) {
continue;
}
$data = $result->get_result();
$status = $result->get_status();
$score = (int) $result->get_score();
$statuses[ $status ] = isset( $statuses[ $status ] ) ? $statuses[ $status ] + 1 : 1;
++$total;
$score_sum += $score;
if ( 'ok' === $status ) {
$score_pass += $score;
}
// Prefer the per-run `message` (contains actual counts/links) over the
// static `description` (generic text defined in the test registration).
$description = isset( $data['message'] ) ? $data['message'] : ( isset( $data['description'] ) ? $data['description'] : '' );
$fix_html = isset( $data['fix'] ) ? $data['fix'] : '';
$findings[] = new Finding(
[
'test_id' => $id,
'category' => $result->get_category(),
'status' => $status,
'score' => $score,
'title' => isset( $data['title'] ) ? $data['title'] : '',
'description' => wp_strip_all_tags( $description ),
'fix_text' => html_entity_decode( wp_strip_all_tags( $fix_html ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ),
'fix_html' => $fix_html,
'fix_hint' => Fix_Hint_Map::get( $id ),
'kb_link' => isset( $data['kb_link'] ) ? $data['kb_link'] : '',
'data' => isset( $data['data'] ) ? $data['data'] : null,
]
);
}
}
$percent = $score_sum > 0 ? (int) round( ( $score_pass / $score_sum ) * 100 ) : 0;
return new Audit_Result(
[
'url' => $analyzer->analyse_url,
'score' => $percent,
'grade' => $this->grade_for( $percent ),
'statuses' => $statuses,
'total_tests' => $total,
'last_run_at' => (int) get_option( 'rank_math_seo_analysis_date', 0 ),
'remote_api_status' => $analyzer->remote_api_succeeded() ? 'ok' : 'unavailable',
'findings' => $findings,
'error' => null,
]
);
}
/**
* Score → grade bucket.
*
* @param int $percent Score percentage 0–100.
* @return string good|average|bad
*/
private function grade_for( $percent ) {
if ( $percent < 50 ) {
return 'bad';
}
if ( $percent < 70 ) {
return 'average';
}
return 'good';
}
}
@@ -0,0 +1,208 @@
<?php
/**
* Ability: rank-math/audit-site-seo
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/audit-site-seo ability.
*/
class Audit_Site_SEO implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Audit runner instance.
*
* @var Audit_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Audit_Runner|null $runner Audit runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Audit_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Audit_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/audit-site-seo',
[
'category' => $this->category,
'label' => esc_html__( 'Audit site SEO', 'seo-by-rank-math' ),
'description' => esc_html__(
"Runs Rank Math's site-wide SEO audit and returns a structured score plus per-test findings with fix hints. Combines local checks with the remote rankmath.com API tests.",
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'refresh' => [
'type' => 'boolean',
'description' => esc_html__( 'Re-run the audit. Defaults to true (always fresh when called by an AI host).', 'seo-by-rank-math' ),
'default' => true,
],
'url' => [
'type' => 'string',
'format' => 'uri',
'description' => esc_html__( "Optional URL to audit. Defaults to this site's home URL. When provided, only remote API tests run (local checks are site-wide).", 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_site_analysis' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$refresh = isset( $input['refresh'] ) ? (bool) $input['refresh'] : true;
$url = isset( $input['url'] ) ? $input['url'] : null;
$result = $this->runner->run( $refresh, $url )->to_array();
rank_math()->tracking->track_ability_executed(
'SEO Audit Run',
[
'score' => isset( $result['score'] ) ? $result['score'] : 0,
'grade' => isset( $result['grade'] ) ? $result['grade'] : '',
'has_url' => ! empty( $url ),
'has_error' => ! empty( $result['error'] ),
],
'rank_math_site_analysis'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'url' => [ 'type' => 'string' ],
'score' => [
'type' => 'integer',
'minimum' => 0,
'maximum' => 100,
],
'grade' => [
'type' => 'string',
'enum' => [ 'good', 'average', 'bad' ],
],
'statuses' => [
'type' => 'object',
'properties' => [
'ok' => [ 'type' => 'integer' ],
'fail' => [ 'type' => 'integer' ],
'warning' => [ 'type' => 'integer' ],
'info' => [ 'type' => 'integer' ],
],
],
'total_tests' => [ 'type' => 'integer' ],
'last_run_at' => [ 'type' => 'integer' ],
'remote_api_status' => [
'type' => 'string',
'enum' => [ 'ok', 'unavailable', 'skipped' ],
],
'findings' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'test_id' => [ 'type' => 'string' ],
'category' => [
'type' => 'string',
'enum' => [ 'priority', 'basic', 'advanced', 'performance', 'security' ],
],
'status' => [
'type' => 'string',
'enum' => [ 'ok', 'fail', 'warning', 'info' ],
],
'score' => [ 'type' => 'integer' ],
'title' => [ 'type' => 'string' ],
'description' => [ 'type' => 'string' ],
'fix_text' => [ 'type' => 'string' ],
'fix_html' => [ 'type' => 'string' ],
'fix_hint' => [ 'type' => [ 'object', 'null' ] ],
'kb_link' => [ 'type' => 'string' ],
'data' => [ 'type' => [ 'object', 'array', 'null' ] ],
],
],
],
'error' => [
'type' => [ 'object', 'null' ],
'properties' => [
'code' => [ 'type' => 'string' ],
'message' => [ 'type' => 'string' ],
],
],
],
];
}
}
@@ -0,0 +1,130 @@
<?php
/**
* Finding value object for the rank-math/audit-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
defined( 'ABSPATH' ) || exit;
/**
* One SEO-audit test result, agent-consumable shape.
*/
class Finding {
/**
* Test identifier.
*
* @var string
*/
public $test_id;
/**
* Test category: priority|basic|advanced|performance|security.
*
* @var string
*/
public $category;
/**
* Test outcome: ok|fail|warning|info.
*
* @var string
*/
public $status;
/**
* Score contribution for this test.
*
* @var int
*/
public $score;
/**
* Human-readable test title.
*
* @var string
*/
public $title;
/**
* Plain-text description of the current result (actual counts/state, not static guidance).
*
* @var string
*/
public $description;
/**
* Plain-text how-to-fix — HTML tags and entities stripped, ready for AI consumption.
*
* @var string
*/
public $fix_text;
/**
* Original how-to-fix HTML, preserved for admin-UI consumers.
*
* @var string
*/
public $fix_html;
/**
* Structured fix hint an agent can act on, or null if none mapped.
*
* @var array|null
*/
public $fix_hint;
/**
* Knowledge-base article URL.
*
* @var string
*/
public $kb_link;
/**
* Free-form per-test supplemental data.
*
* @var mixed
*/
public $data;
/**
* Constructor.
*
* @param array $args See properties.
*/
public function __construct( array $args ) {
foreach ( $args as $key => $value ) {
if ( property_exists( $this, $key ) ) {
$this->{$key} = $value;
}
}
}
/**
* Serialize to array.
*
* @return array
*/
public function to_array() {
return [
'test_id' => $this->test_id,
'category' => $this->category,
'status' => $this->status,
'score' => (int) $this->score,
'title' => $this->title,
'description' => $this->description,
'fix_text' => $this->fix_text,
'fix_html' => $this->fix_html,
'fix_hint' => $this->fix_hint,
'kb_link' => $this->kb_link,
'data' => $this->data,
];
}
}
@@ -0,0 +1,94 @@
<?php
/**
* Fix hint map for the rank-math/audit-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
defined( 'ABSPATH' ) || exit;
/**
* Maps SEO-audit test IDs to structured fix hints an agent can act on.
*
* Kind:
* - 'wp_admin' → user/agent should open this WP admin page
* - 'setting' → fix is a Rank Math setting (`rank-math-options-{section}`)
* - 'ability' → another Rank Math ability can fix it (only entries for shipped abilities)
* - 'manual' → content edit per post; no single setting flip will resolve it
*
* Tests not in this map return null for fix_hint; the agent falls back to the
* `fix_html` text. Entries are added here as new abilities ship.
*/
class Fix_Hint_Map {
/**
* Retrieves the fix hint for a given test ID.
*
* @param string $test_id The ID of the test for which to retrieve a fix hint.
* @return array|null The fix hint array or null if not found.
*/
public static function get( $test_id ) {
$map = [
// Single WP setting fix.
'site_description' => [
'kind' => 'wp_admin',
'target' => 'options-general.php',
],
'permalink_structure' => [
'kind' => 'wp_admin',
'target' => 'options-permalink.php',
],
'blog_public' => [
'kind' => 'wp_admin',
'target' => 'options-reading.php',
],
// Rank Math settings panels.
'sitemaps' => [
'kind' => 'setting',
'target' => 'rank-math-options-sitemap',
],
'noindex' => [
'kind' => 'setting',
'target' => 'rank-math-options-titles',
],
'opengraph' => [
'kind' => 'setting',
'target' => 'rank-math-options-titles',
],
'schema' => [
'kind' => 'setting',
'target' => 'rank-math-options-titles',
],
'robots_txt' => [
'kind' => 'setting',
'target' => 'rank-math-options-general',
],
// Per-post content edits — no single flip; agent must walk posts.
'h1_heading' => [
'kind' => 'manual',
'target' => 'edit_post_content',
],
'h2_headings' => [
'kind' => 'manual',
'target' => 'edit_post_content',
],
'keywords_meta' => [
'kind' => 'manual',
'target' => 'edit_post_keywords',
],
'title_length' => [
'kind' => 'manual',
'target' => 'edit_post_titles',
],
];
return isset( $map[ $test_id ] ) ? $map[ $test_id ] : null;
}
}
@@ -0,0 +1,430 @@
<?php
/**
* Fix runner service for the rank-math/fix-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Applies automatic fixes for failing SEO analysis tests.
*/
class Fix_Runner {
/**
* Maximum posts to process in a single synchronous fix call.
*/
const POST_LIMIT = 100;
/**
* Apply the fix for a given test and return a result summary.
*
* @param string $test_id SEO analysis test identifier.
* @param array $input Raw ability input (may include 'value', 'post_limit').
* @return array { fixed: bool, summary: string, details: array }
*/
public function fix( $test_id, array $input = [] ) {
$handler = 'fix_' . $test_id;
if ( ! method_exists( $this, $handler ) ) {
return $this->cannot_fix(
sprintf(
/* translators: %s: test ID */
__( 'No automatic fix is available for test "%s". Use the fix_text guidance to resolve it manually.', 'seo-by-rank-math' ),
$test_id
)
);
}
return $this->{$handler}( $input );
}
/**
* Fix: make the site visible to search engines.
*
* @param array $input Unused.
* @return array
*/
protected function fix_blog_public( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
update_option( 'blog_public', 1 );
return $this->ok( __( 'Site visibility set to public. Search engines can now index your site.', 'seo-by-rank-math' ) );
}
/**
* Fix: set permalink structure to /%postname%/.
*
* @param array $input Unused.
* @return array
*/
protected function fix_permalink_structure( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
global $wp_rewrite;
if ( '/%postname%/' === get_option( 'permalink_structure' ) ) {
return $this->ok( __( 'Permalink structure is already set to /%postname%/.', 'seo-by-rank-math' ) );
}
update_option( 'permalink_structure', '/%postname%/' );
$wp_rewrite->set_permalink_structure( '/%postname%/' );
$wp_rewrite->flush_rules( true );
return $this->ok( __( 'Permalink structure set to /%postname%/ and rewrite rules flushed.', 'seo-by-rank-math' ) );
}
/**
* Fix: set the site tagline to a custom value.
*
* Requires `value` in input — refuses if missing or looks like the default.
*
* @param array $input Must contain 'value'.
* @return array
*/
protected function fix_site_description( array $input ) {
$value = isset( $input['value'] ) ? sanitize_text_field( $input['value'] ) : '';
if ( empty( $value ) ) {
return $this->cannot_fix(
__( 'A "value" input is required to set the site tagline. Provide a short, unique description of your site.', 'seo-by-rank-math' )
);
}
if ( 'just another wordpress site' === strtolower( $value ) ) { // phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText
return $this->cannot_fix(
__( 'The provided tagline is the default WordPress value. Please supply a unique tagline.', 'seo-by-rank-math' )
);
}
update_option( 'blogdescription', $value );
return $this->ok(
sprintf(
/* translators: %s: tagline value */
__( 'Site tagline updated to: "%s".', 'seo-by-rank-math' ),
$value
)
);
}
// -------------------------------------------------------------------------
// Rank Math module fixes
// -------------------------------------------------------------------------
/**
* Fix: enable the Rank Math sitemap module.
*
* @param array $input Unused.
* @return array
*/
protected function fix_sitemaps( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
Helper::update_modules( [ 'sitemap' => 'on' ] );
return $this->ok( __( 'Sitemap module enabled. Your XML sitemap is now active.', 'seo-by-rank-math' ) );
}
/**
* Fix: enable the Rank Math schema (rich snippet) module.
*
* @param array $input Unused.
* @return array
*/
protected function fix_schema( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
Helper::update_modules( [ 'rich-snippet' => 'on' ] );
return $this->ok( __( 'Schema / rich snippet module enabled.', 'seo-by-rank-math' ) );
}
// -------------------------------------------------------------------------
// Rank Math settings fixes
// -------------------------------------------------------------------------
/**
* Fix: ensure the global robots setting does not include noindex.
*
* @param array $input Unused.
* @return array
*/
protected function fix_noindex( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
$titles = (array) get_option( 'rank-math-options-titles', [] );
$robots = isset( $titles['robots_global'] ) ? (array) $titles['robots_global'] : [ 'index', 'follow' ];
$robots = array_diff( $robots, [ 'noindex' ] );
if ( ! in_array( 'index', $robots, true ) ) {
$robots[] = 'index';
}
$titles['robots_global'] = array_values( $robots );
update_option( 'rank-math-options-titles', $titles );
return $this->ok( __( 'Global robots setting updated to allow indexing. Run a fresh audit to confirm the remote API test passes.', 'seo-by-rank-math' ) );
}
/**
* Fix: OpenGraph is always enabled in Rank Math — explain to the AI.
*
* @param array $input Unused.
* @return array
*/
protected function fix_opengraph( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
return $this->cannot_fix(
__( 'OpenGraph output is always enabled in Rank Math. If this test is failing, the remote audit API may need a fallback Open Graph image. Set one at Rank Math → Titles & Meta → Global Meta → Open Graph Thumbnail.', 'seo-by-rank-math' )
);
}
/**
* Fix: write a safe default robots.txt content into Rank Math settings.
*
* @param array $input Unused.
* @return array
*/
protected function fix_robots_txt( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
$general = (array) get_option( 'rank-math-options-general', [] );
if ( isset( $general['robots_txt_content'] ) && '' !== trim( $general['robots_txt_content'] ) ) {
return $this->ok( __( 'Robots.txt content is already configured in Rank Math settings.', 'seo-by-rank-math' ) );
}
$general['robots_txt_content'] = "User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php";
update_option( 'rank-math-options-general', $general );
return $this->ok( __( 'Default robots.txt content written to Rank Math settings.', 'seo-by-rank-math' ) );
}
// -------------------------------------------------------------------------
// Per-post bulk fixes
// -------------------------------------------------------------------------
/**
* Fix: set a focus keyword on every published post that is missing one.
*
* The keyword is derived from the first 3 significant words of the post title.
* Accepts optional 'post_limit' input (default: POST_LIMIT).
*
* @param array $input Optional: post_limit (int).
* @return array
*/
protected function fix_focus_keywords( array $input ) {
$limit = isset( $input['post_limit'] ) ? absint( $input['post_limit'] ) : self::POST_LIMIT;
$limit = max( 1, min( $limit, 500 ) );
$types = Helper::get_allowed_post_types();
if ( empty( $types ) ) {
return $this->cannot_fix( __( 'No indexable post types are configured in Rank Math.', 'seo-by-rank-math' ) );
}
$posts = get_posts(
[
'post_type' => $types,
'post_status' => 'publish',
'posts_per_page' => $limit,
'meta_query' => [ // phpcs:ignore WordPress.DB.SlowDBQuery
[
'key' => 'rank_math_focus_keyword',
'compare' => 'NOT EXISTS',
],
],
'fields' => 'ids',
]
);
if ( empty( $posts ) ) {
return $this->ok( __( 'All published posts already have a focus keyword set.', 'seo-by-rank-math' ) );
}
$updated = 0;
$truncated = count( $posts ) >= $limit;
foreach ( $posts as $post_id ) {
$title = get_the_title( $post_id );
$keyword = $this->keyword_from_title( $title );
if ( empty( $keyword ) ) {
continue;
}
update_post_meta( $post_id, 'rank_math_focus_keyword', $keyword );
++$updated;
}
$summary = sprintf(
/* translators: 1: count updated, 2: total found */
__( 'Set focus keywords on %1$d posts (derived from post titles).', 'seo-by-rank-math' ),
$updated
);
if ( $truncated ) {
$summary .= ' ' . sprintf(
/* translators: %d: post_limit */
__( 'Results were limited to %d posts — run again to continue.', 'seo-by-rank-math' ),
$limit
);
}
return $this->ok(
$summary,
[
'updated' => $updated,
'truncated' => $truncated,
]
);
}
/**
* Fix: update the focus keyword to match the existing post title for posts where it doesn't.
*
* Changing the focus keyword (not the title) is safe: it doesn't affect URLs or published content.
* Accepts optional 'post_limit' input (default: POST_LIMIT).
*
* @param array $input Optional: post_limit (int).
* @return array
*/
protected function fix_post_titles( array $input ) {
global $wpdb;
$limit = isset( $input['post_limit'] ) ? absint( $input['post_limit'] ) : self::POST_LIMIT;
$limit = max( 1, min( $limit, 500 ) );
$types = Helper::get_allowed_post_types();
if ( empty( $types ) ) {
return $this->cannot_fix( __( 'No indexable post types are configured in Rank Math.', 'seo-by-rank-math' ) );
}
$in_post_types = "'" . implode( "','", array_map( 'esc_sql', $types ) ) . "'";
// Reuse the same query as the test — posts with focus keyword set but keyword not in title.
$meta_query = new \WP_Meta_Query(
[
'relation' => 'AND',
[
'key' => 'rank_math_focus_keyword',
'compare' => 'EXISTS',
],
[
'relation' => 'OR',
[
'key' => 'rank_math_robots',
'value' => 'noindex',
'compare' => 'NOT LIKE',
],
[
'key' => 'rank_math_robots',
'compare' => 'NOT EXISTS',
],
],
]
);
$mq_sql = $meta_query->get_sql( 'post', $wpdb->posts, 'ID' );
// phpcs:disable WordPress.DB.DirectDatabaseQuery
$rows = $wpdb->get_results(
$wpdb->prepare(
// phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder
"SELECT {$wpdb->posts}.ID, {$wpdb->posts}.post_title
FROM {$wpdb->posts} {$mq_sql['join']}
WHERE 1=1 {$mq_sql['where']}
AND {$wpdb->posts}.post_type IN ({$in_post_types})
AND {$wpdb->posts}.post_status = 'publish'
AND REPLACE( {$wpdb->posts}.post_title, %s, %s ) NOT LIKE
CONCAT( %s, SUBSTRING_INDEX( {$wpdb->postmeta}.meta_value, %s, 1 ), %s )
GROUP BY {$wpdb->posts}.ID
LIMIT %d",
'&amp;',
'&',
'%',
',',
'%',
$limit
)
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery
if ( empty( $rows ) ) {
return $this->ok( __( 'All posts with focus keywords already include them in their titles.', 'seo-by-rank-math' ) );
}
$updated = 0;
$truncated = count( $rows ) >= $limit;
foreach ( $rows as $row ) {
$keyword = $this->keyword_from_title( $row->post_title );
if ( empty( $keyword ) ) {
continue;
}
update_post_meta( (int) $row->ID, 'rank_math_focus_keyword', $keyword );
++$updated;
}
$summary = sprintf(
/* translators: %d: count updated */
__( 'Updated focus keywords on %d posts to match their titles.', 'seo-by-rank-math' ),
$updated
);
if ( $truncated ) {
$summary .= ' ' . sprintf(
/* translators: %d: post_limit */
__( 'Results were limited to %d posts — run again to continue.', 'seo-by-rank-math' ),
$limit
);
}
return $this->ok(
$summary,
[
'updated' => $updated,
'truncated' => $truncated,
]
);
}
/**
* Derive a focus keyword from a post title.
*
* Returns the first 3 words, lower-cased, with punctuation stripped.
* Returns empty string if nothing usable remains.
*
* @param string $title Post title.
* @return string
*/
private function keyword_from_title( $title ) {
$words = preg_split( '/\s+/', strtolower( html_entity_decode( $title, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ) );
$words = array_values(
array_filter(
$words,
function ( $w ) {
return ! empty( preg_replace( '/[^a-z0-9]/i', '', $w ) );
}
)
);
return implode( ' ', array_slice( $words, 0, 3 ) );
}
/**
* Return a successful fix result.
*
* @param string $summary Human-readable summary.
* @param array $details Optional extra data.
* @return array
*/
private function ok( $summary, array $details = [] ) {
return [
'fixed' => true,
'summary' => $summary,
'details' => $details,
];
}
/**
* Return a result indicating the fix could not be applied.
*
* @param string $summary Reason why the fix could not be applied.
* @return array
*/
private function cannot_fix( $summary ) {
return [
'fixed' => false,
'summary' => $summary,
'details' => [],
];
}
}
@@ -0,0 +1,173 @@
<?php
/**
* Ability: rank-math/fix-site-seo
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/fix-site-seo ability.
*/
class Fix_Site_SEO implements Ability_Interface {
/**
* Fixable test IDs — kept in sync with Fix_Runner handler methods.
*/
const FIXABLE_TEST_IDS = [
'blog_public',
'permalink_structure',
'site_description',
'sitemaps',
'schema',
'noindex',
'opengraph',
'robots_txt',
'focus_keywords',
'post_titles',
];
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Fix runner instance.
*
* @var Fix_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Fix_Runner|null $runner Fix runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Fix_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Fix_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/fix-site-seo',
[
'category' => $this->category,
'label' => esc_html__( 'Fix site SEO', 'seo-by-rank-math' ),
'description' => esc_html__(
'Applies an automatic fix for a single failing Rank Math SEO test. Pass the test_id from an audit-site-seo finding. Some fixes require additional input (e.g. value for site_description). Bulk fixes accept an optional post_limit.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'test_id' ],
'properties' => [
'test_id' => [
'type' => 'string',
'enum' => self::FIXABLE_TEST_IDS,
'description' => esc_html__( 'The SEO test identifier to fix (from audit-site-seo findings).', 'seo-by-rank-math' ),
],
'value' => [
'type' => 'string',
'description' => esc_html__( 'Required for site_description: the new tagline to set.', 'seo-by-rank-math' ),
],
'post_limit' => [
'type' => 'integer',
'minimum' => 1,
'maximum' => 500,
'description' => esc_html__( 'For bulk post fixes (focus_keywords, post_titles): max posts to update in one call. Default 100.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => false,
'destructive' => false,
'idempotent' => false,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_site_analysis' ) && current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$test_id = (string) $input['test_id'];
$result = $this->runner->fix( $test_id, (array) $input );
rank_math()->tracking->track_ability_executed(
'SEO Audit Test Fixed',
[
'test_id' => $test_id,
'fixed' => ! empty( $result['fixed'] ),
],
'rank_math_site_analysis'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'fixed' => [ 'type' => 'boolean' ],
'summary' => [ 'type' => 'string' ],
'details' => [ 'type' => 'object' ],
],
];
}
}
@@ -0,0 +1,89 @@
<?php
/**
* Subscriber for SEO Analysis abilities.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the SEO Analysis ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for SEO Analysis abilities.
*/
const CATEGORY_SLUG = 'rank-math-seo-analysis';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_audit_site_seo' );
$this->action( 'wp_abilities_api_init', 'register_fix_site_seo' );
}
/**
* Register the SEO Analysis ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'SEO Analysis', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to audit and fix site-wide SEO issues.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/audit-site-seo ability.
*
* @return void
*/
public function register_audit_site_seo(): void {
( new Audit_Site_SEO( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/fix-site-seo ability.
*
* @return void
*/
public function register_fix_site_seo(): void {
( new Fix_Site_SEO( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,195 @@
<?php
/**
* Abstract base class for Settings abilities.
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Shared infrastructure for all Settings abilities.
*
* Provides the constructor, check_permissions(), option-reader helpers,
* apply_toggle_fields(), save_and_reset(), build_meta(), and write_success_schema()
* so concrete classes only need to implement register() and execute().
*/
abstract class Abstract_Ability implements Ability_Interface {
/**
* Allowed robots meta directive values — shared across abilities.
*/
const ROBOTS_DIRECTIVES = [ 'index', 'noindex', 'nofollow', 'noarchive', 'noimageindex', 'nosnippet' ];
/**
* Ability category slug.
*
* @var string
*/
protected $category;
/**
* Shared meta args.
*
* @var array
*/
protected $shared_meta;
/**
* WordPress capability required to execute this ability.
*
* @var string
*/
private $required_capability;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param string $required_capability WP capability checked in check_permissions().
*/
public function __construct( string $category, array $shared_meta, string $required_capability ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->required_capability = $required_capability;
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( $this->required_capability );
}
/**
* Current raw general option.
*
* @return array
*/
protected function get_general_option(): array {
return (array) get_option( 'rank-math-options-general', [] );
}
/**
* Current raw titles option.
*
* @return array
*/
protected function get_titles_option(): array {
return (array) get_option( 'rank-math-options-titles', [] );
}
/**
* Currently active module slugs.
*
* @return array<int, string>
*/
protected function get_active_modules(): array {
return (array) get_option( 'rank_math_modules', [] );
}
/**
* Accessible post type slugs.
*
* @return array<int, string>
*/
protected function get_accessible_post_types(): array {
return array_keys( Helper::get_accessible_post_types() );
}
/**
* Apply boolean-to-on/off toggle fields from input onto an option array.
*
* @param array $option Target option array (modified in-place).
* @param array $input Ability input.
* @param string[] $fields Field names to apply.
* @return void
*/
protected function apply_toggle_fields( array &$option, array $input, array $fields ): void {
foreach ( $fields as $field ) {
if ( isset( $input[ $field ] ) ) {
$option[ $field ] = $input[ $field ] ? 'on' : 'off';
}
}
}
/**
* Persist settings and flush the in-memory cache.
*
* @param array|null $general Updated general section, or null to leave untouched.
* @param array|null $titles Updated titles section, or null to leave untouched.
* @param array|null $sitemap Updated sitemap section, or null to leave untouched.
* @return void
*/
protected function save_and_reset( ?array $general, ?array $titles, ?array $sitemap ): void {
Helper::update_all_settings( $general, $titles, $sitemap );
rank_math()->settings->reset();
}
/**
* Build the meta array for wp_register_ability(), merging in annotations.
*
* @param bool $read_only Whether this ability only reads data.
* @return array
*/
protected function build_meta( bool $read_only ): array {
return array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => $read_only,
'destructive' => false,
'idempotent' => true,
],
]
);
}
/**
* JSON schema fragment common to all write-ability success responses.
*
* @param bool $with_error Include the error property.
* @param string $updated_description Description for the updated field.
* @return array
*/
protected function write_success_schema( bool $with_error = false, string $updated_description = 'List of field names that were updated.' ): array {
$schema = [
'type' => 'object',
'properties' => [
'saved' => [
'type' => 'boolean',
'description' => 'Whether the update was saved.',
],
'updated' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
'description' => $updated_description,
],
],
];
if ( $with_error ) {
$schema['properties']['error'] = [
'type' => 'object',
'description' => 'Present only when the update failed validation.',
'properties' => [
'code' => [ 'type' => 'string' ],
'message' => [ 'type' => 'string' ],
],
];
}
return $schema;
}
}
@@ -0,0 +1,138 @@
<?php
/**
* Ability: rank-math/get-llms-txt
*
* @since 1.0.278
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
use RankMath\LLMS\LLMS_Txt;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-llms-txt ability.
*
* Delegates entirely to LLMS_Txt::output(), capturing its echoed Markdown
* output via an output buffer rather than reimplementing the generation logic.
*/
class Get_Llms_Txt extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_general' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-llms-txt',
[
'category' => $this->category,
'label' => esc_html__( 'Get llms.txt', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns whether the llms.txt file is enabled, its URL, and the current generated Markdown content.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( true ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$enabled = $this->is_enabled();
$result = [
'enabled' => $enabled,
'url' => home_url( '/llms.txt' ),
'content' => $enabled ? $this->fetch_content() : '',
];
rank_math()->tracking->track_ability_executed(
'LLMs Txt Fetched',
[ 'enabled' => $enabled ],
'rank_math_general'
);
return $result;
}
/**
* Whether the llms.txt module is active. Extracted for testability.
*
* @return bool
*/
protected function is_enabled(): bool {
return Helper::is_module_active( 'llms-txt' );
}
/**
* Capture the LLMS_Txt::output() Markdown content via an output buffer.
*
* Output() also sends a couple of headers (Content-Type: text/plain,
* X-Robots-Tag) as a side effect of reuse — harmless here since the
* REST/MCP response sends its own headers afterward. Extracted for
* testability.
*
* @return string
*/
protected function fetch_content(): string {
ob_start();
( new LLMS_Txt() )->output();
return (string) ob_get_clean();
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'enabled' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether the llms.txt module is active.', 'seo-by-rank-math' ),
],
'url' => [
'type' => 'string',
'description' => esc_html__( 'The URL of the llms.txt file.', 'seo-by-rank-math' ),
],
'content' => [
'type' => 'string',
'description' => esc_html__( 'The generated llms.txt Markdown content. Empty when the module is disabled.', 'seo-by-rank-math' ),
],
],
];
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Ability: rank-math/get-robots-txt
*
* @since 1.0.278
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Robots_Txt;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-robots-txt ability.
*/
class Get_Robots_Txt extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_general' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-robots-txt',
[
'category' => $this->category,
'label' => esc_html__( 'Get robots.txt', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the current robots.txt content managed by Rank Math.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
],
'output_schema' => [
'type' => 'object',
'properties' => [
'content' => [
'type' => 'string',
'description' => esc_html__( 'The current robots.txt content: the real file contents when a physical robots.txt exists, otherwise the content Rank Math generates (custom override or computed default).', 'seo-by-rank-math' ),
],
'exists' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether a physical robots.txt file exists in the site root.', 'seo-by-rank-math' ),
],
'public' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether the site is set to be visible to search engines (Settings > Reading > Search engine visibility).', 'seo-by-rank-math' ),
],
],
],
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( true ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$data = $this->get_robots_data();
rank_math()->tracking->track_ability_executed(
'Robots Txt Fetched',
[],
'rank_math_general'
);
return [
'content' => $data['default'],
'exists' => ! empty( $data['exists'] ),
'public' => 0 !== absint( $data['public'] ),
];
}
/**
* Fetch raw data from Robots_Txt. Extracted for testability.
*
* @return array
*/
protected function get_robots_data(): array {
return Robots_Txt::get_robots_data();
}
}
@@ -0,0 +1,191 @@
<?php
/**
* Ability: rank-math/get-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-settings ability.
*/
class Get_Settings extends Abstract_Ability {
/**
* Keys stripped from the general section before returning to AI — contain credentials or internal state.
*/
const SENSITIVE_GENERAL_KEYS = [
'facebook_secret',
'console_profile',
'searchConsole',
'analyticsData',
'analytics',
'console_caching_control',
];
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'manage_options' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Get settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the full normalized Rank Math settings snapshot: all four sections (general, titles, sitemap, instant_indexing), active module status, and auto-update state. Call this first in any AI configuration flow to understand what is already configured before making changes.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'sections' => [
'type' => 'array',
'description' => esc_html__( 'Return only these top-level sections. Omit to return the full snapshot.', 'seo-by-rank-math' ),
'items' => [
'type' => 'string',
'enum' => [ 'general', 'titles', 'sitemap', 'instant_indexing', 'modules', 'auto_update' ],
],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( true ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$settings = rank_math()->settings->all();
foreach ( self::SENSITIVE_GENERAL_KEYS as $key ) {
unset( $settings['general'][ $key ] );
}
$settings['modules'] = $this->get_module_status();
$settings['auto_update'] = $this->get_auto_update_setting();
if ( ! empty( $input['sections'] ) ) {
$settings = array_intersect_key( $settings, array_fill_keys( $input['sections'], true ) );
}
rank_math()->tracking->track_ability_executed(
'Settings Fetched',
[ 'sections' => array_keys( $settings ) ],
'manage_options'
);
return $settings;
}
/**
* Build a map of user-facing modules with their effective active status.
*
* Excludes internal modules (always loaded, not user-toggleable) and
* skip-only entries. Modules whose dependencies are not met (disabled = true)
* are always reported as inactive regardless of the stored option value.
*
* @return array<string, bool>
*/
private function get_module_status(): array {
$active_modules = $this->get_active_modules();
$status = [];
foreach ( rank_math()->manager->modules as $slug => $module ) {
$only = $module->get( 'only' );
// Internal and skip-only modules are not user-configurable.
if ( 'internal' === $only || 'skip' === $only ) {
continue;
}
// A module whose dependency is missing is always inactive.
if ( $module->get( 'disabled', false ) ) {
$status[ $slug ] = false;
continue;
}
$status[ $slug ] = in_array( $slug, $active_modules, true );
}
return $status;
}
/**
* Whether automatic plugin updates are enabled. Extracted for testability.
*
* @return bool
*/
protected function get_auto_update_setting(): bool {
return Helper::get_auto_update_setting();
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'description' => 'Normalized plugin settings snapshot.',
'properties' => [
'general' => [
'type' => 'object',
'description' => 'General settings (rank-math-options-general). Boolean values are normalized from on/off storage strings.',
],
'titles' => [
'type' => 'object',
'description' => 'Titles & Meta settings (rank-math-options-titles).',
],
'sitemap' => [
'type' => 'object',
'description' => 'Sitemap settings (rank-math-options-sitemap).',
],
'instant_indexing' => [
'type' => 'object',
'description' => 'Instant Indexing settings (rank-math-options-instant-indexing).',
],
'modules' => [
'type' => 'object',
'description' => 'Map of all registered module slugs to their active status.',
'additionalProperties' => [ 'type' => 'boolean' ],
],
'auto_update' => [
'type' => 'boolean',
'description' => 'Whether automatic plugin updates are enabled.',
],
],
];
}
}
@@ -0,0 +1,91 @@
<?php
/**
* Ability: rank-math/get-system-status
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Status\System_Status;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-system-status ability.
*
* Delegates entirely to System_Status::get_json_data() which already
* collects Rank Math health data and WordPress core / server info.
*/
class Get_System_Status extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'manage_options' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-system-status',
[
'category' => $this->category,
'label' => esc_html__( 'Get system status', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns a structured system health snapshot identical to Status & Tools → System Status in the admin: Rank Math version, plan, DB table health, Google token status, WordPress core info, server environment, and active plugins. Call this alongside get-settings at the start of any AI configuration flow to detect environment issues before making changes.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
],
'output_schema' => [
'type' => 'object',
'description' => 'System info sections keyed by section ID (e.g. rank-math, wp-core, wp-server).',
],
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( true ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$result = $this->fetch_system_data()['systemInfo'];
rank_math()->tracking->track_ability_executed(
'System Status Fetched',
[],
'manage_options'
);
return $result;
}
/**
* Fetch raw data from System_Status. Extracted for testability.
*
* @return array
*/
protected function fetch_system_data(): array {
return System_Status::get_json_data();
}
}
@@ -0,0 +1,172 @@
<?php
/**
* Ability: rank-math/set-breadcrumb-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-breadcrumb-settings ability.
*/
class Set_Breadcrumb_Settings extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_general' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-breadcrumb-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set breadcrumb settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates breadcrumb display settings: enabling breadcrumbs, the separator, home link visibility/label/URL, a prefix before the trail, archive/search/404 label formats, ancestor category display, hiding the taxonomy name, removing the current post title, and showing the blog page. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'breadcrumbs' => [
'type' => 'boolean',
'title' => esc_html__( 'Enable Breadcrumbs', 'seo-by-rank-math' ),
'description' => esc_html__( 'Enable the Breadcrumbs feature.', 'seo-by-rank-math' ),
],
'breadcrumbs_separator' => [
'type' => 'string',
'title' => esc_html__( 'Separator Character', 'seo-by-rank-math' ),
'description' => esc_html__( 'Character to display between breadcrumb links.', 'seo-by-rank-math' ),
],
'breadcrumbs_home' => [
'type' => 'boolean',
'title' => esc_html__( 'Show Home Link', 'seo-by-rank-math' ),
'description' => esc_html__( 'Show a link to the homepage at the start of the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_home_label' => [
'type' => 'string',
'title' => esc_html__( 'Home Label', 'seo-by-rank-math' ),
'description' => esc_html__( 'Label used for the homepage link in the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_home_link' => [
'type' => 'string',
'title' => esc_html__( 'Home Link', 'seo-by-rank-math' ),
'description' => esc_html__( 'URL used for the homepage link in the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_prefix' => [
'type' => 'string',
'title' => esc_html__( 'Prefix Breadcrumb', 'seo-by-rank-math' ),
'description' => esc_html__( 'Text to show before the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_archive_format' => [
'type' => 'string',
'title' => esc_html__( 'Archive Format', 'seo-by-rank-math' ),
'description' => esc_html__( 'Label format used for archive pages in the breadcrumb trail. Include a placeholder token for the archive title.', 'seo-by-rank-math' ),
],
'breadcrumbs_search_format' => [
'type' => 'string',
'title' => esc_html__( 'Search Results Format', 'seo-by-rank-math' ),
'description' => esc_html__( 'Label format used for search results pages in the breadcrumb trail. Include a placeholder token for the search query.', 'seo-by-rank-math' ),
],
'breadcrumbs_404_label' => [
'type' => 'string',
'title' => esc_html__( '404 Label', 'seo-by-rank-math' ),
'description' => esc_html__( 'Label used for the 404 error item in the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_remove_post_title' => [
'type' => 'boolean',
'title' => esc_html__( 'Hide Post Title', 'seo-by-rank-math' ),
'description' => esc_html__( 'Hide the current post/page title from the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_ancestor_categories' => [
'type' => 'boolean',
'title' => esc_html__( 'Show Category(s)', 'seo-by-rank-math' ),
'description' => esc_html__( 'If the category is a child category, show all ancestor categories in the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_hide_taxonomy_name' => [
'type' => 'boolean',
'title' => esc_html__( 'Hide Taxonomy Name', 'seo-by-rank-math' ),
'description' => esc_html__( 'Hide the current taxonomy term name from the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_blog_page' => [
'type' => 'boolean',
'title' => esc_html__( 'Show Blog Page', 'seo-by-rank-math' ),
'description' => esc_html__( 'Show the blog page in the breadcrumb trail. Only applies when a static homepage is set.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$general = $this->get_general_option();
$this->apply_toggle_fields(
$general,
$input,
[
'breadcrumbs',
'breadcrumbs_home',
'breadcrumbs_remove_post_title',
'breadcrumbs_ancestor_categories',
'breadcrumbs_hide_taxonomy_name',
'breadcrumbs_blog_page',
]
);
foreach ( [ 'breadcrumbs_separator', 'breadcrumbs_home_label', 'breadcrumbs_prefix', 'breadcrumbs_archive_format', 'breadcrumbs_search_format', 'breadcrumbs_404_label' ] as $field ) {
if ( isset( $input[ $field ] ) ) {
$general[ $field ] = sanitize_text_field( $input[ $field ] );
}
}
if ( isset( $input['breadcrumbs_home_link'] ) ) {
$general['breadcrumbs_home_link'] = esc_url_raw( $input['breadcrumbs_home_link'] );
}
$this->save_and_reset( $general, null, null );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Breadcrumb Settings Updated',
[ 'fields_updated' => $keys ],
'rank_math_general'
);
return [
'saved' => true,
'updated' => $keys,
];
}
}
@@ -0,0 +1,150 @@
<?php
/**
* Ability: rank-math/set-global-seo-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-global-seo-settings ability.
*/
class Set_Global_Seo_Settings extends Abstract_Ability {
/**
* Allowed values for the twitter_card_type field.
*/
const TWITTER_CARD_TYPES = [ 'summary_large_image', 'summary_card' ];
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_titles' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-global-seo-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set global SEO settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates site-wide SEO defaults: global robots meta directives, whether to noindex empty taxonomy archives, the title separator character, title capitalization, and the default Twitter card type. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'robots_global' => [
'type' => 'array',
'items' => [
'type' => 'string',
'enum' => self::ROBOTS_DIRECTIVES,
],
'description' => esc_html__( 'Global robots meta directives applied site-wide (e.g. ["index"], ["noindex","nofollow"]).', 'seo-by-rank-math' ),
],
'noindex_empty_taxonomies' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether to noindex taxonomy archives that have no posts assigned.', 'seo-by-rank-math' ),
],
'title_separator' => [
'type' => 'string',
'description' => esc_html__( 'Character used to separate parts of the SEO title (e.g. "-", "|", "&mdash;"). A custom string is also accepted.', 'seo-by-rank-math' ),
],
'capitalize_titles' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether to capitalize the first letter of every word in SEO titles.', 'seo-by-rank-math' ),
],
'twitter_card_type' => [
'type' => 'string',
'enum' => self::TWITTER_CARD_TYPES,
'description' => esc_html__( 'Default Twitter card type used when sharing content.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
if ( isset( $input['robots_global'] ) ) {
foreach ( (array) $input['robots_global'] as $value ) {
if ( ! in_array( $value, self::ROBOTS_DIRECTIVES, true ) ) {
return [
'error' => [
'code' => 'invalid_robots_global',
'message' => esc_html__( 'robots_global may only contain: index, noindex, nofollow, noarchive, noimageindex, nosnippet.', 'seo-by-rank-math' ),
],
];
}
}
}
if ( isset( $input['twitter_card_type'] ) && ! in_array( $input['twitter_card_type'], self::TWITTER_CARD_TYPES, true ) ) {
return [
'error' => [
'code' => 'invalid_twitter_card_type',
'message' => esc_html__( 'twitter_card_type must be either "summary_large_image" or "summary_card".', 'seo-by-rank-math' ),
],
];
}
$titles = $this->get_titles_option();
if ( isset( $input['robots_global'] ) ) {
$titles['robots_global'] = array_map( 'sanitize_text_field', (array) $input['robots_global'] );
}
$this->apply_toggle_fields( $titles, $input, [ 'noindex_empty_taxonomies', 'capitalize_titles' ] );
if ( isset( $input['title_separator'] ) ) {
$titles['title_separator'] = sanitize_text_field( $input['title_separator'] );
}
if ( isset( $input['twitter_card_type'] ) ) {
$titles['twitter_card_type'] = sanitize_text_field( $input['twitter_card_type'] );
}
$this->save_and_reset( null, $titles, null );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Global SEO Settings Updated',
[ 'fields_updated' => $keys ],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $keys,
];
}
}
@@ -0,0 +1,189 @@
<?php
/**
* Ability: rank-math/set-homepage-seo
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-homepage-seo ability.
*
* Automatically detects whether the homepage is a static page or the latest-posts
* feed and writes to the appropriate storage in each case:
*/
class Set_Homepage_Seo extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_titles' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-homepage-seo',
[
'category' => $this->category,
'label' => esc_html__( 'Set homepage SEO', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates the SEO title, meta description, and focus keyword for the site homepage. Automatically detects whether the homepage is a static page or a latest-posts feed and writes to the correct storage in each case. Call get-settings first to see current homepage values. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'title' => [
'type' => 'string',
'title' => esc_html__( 'SEO Title', 'seo-by-rank-math' ),
'description' => esc_html__( 'SEO title for the homepage. Supports Rank Math title variables (e.g. %sitename%, %sep%, %sitedesc%). For static-page homepages, stored as post meta; for latest-posts homepages, stored in Titles & Meta settings.', 'seo-by-rank-math' ), //phpcs:ignore WordPress.WP.I18n
],
'description' => [
'type' => 'string',
'title' => esc_html__( 'Meta Description', 'seo-by-rank-math' ),
'description' => esc_html__( 'Meta description for the homepage. For static-page homepages, stored as post meta; for latest-posts homepages, stored in Titles & Meta settings.', 'seo-by-rank-math' ),
],
'focus_keyword' => [
'type' => 'string',
'title' => esc_html__( 'Focus Keyword', 'seo-by-rank-math' ),
'description' => esc_html__( 'Primary focus keyword for the homepage. Only applicable when the homepage is a static page — ignored for latest-posts homepages.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
if ( empty( $input ) ) {
return [
'error' => [
'code' => 'no_fields',
'message' => esc_html__( 'No fields provided. Pass at least one of: title, description, focus_keyword.', 'seo-by-rank-math' ),
],
];
}
if ( 'page' === get_option( 'show_on_front' ) ) {
return $this->update_static_page( $input );
}
return $this->update_latest_posts( $input );
}
/**
* Write title/description post meta on the static front page.
*
* @param array $input Ability input.
* @return array
*/
private function update_static_page( array $input ): array {
$page_id = (int) get_option( 'page_on_front' );
if ( ! $page_id ) {
return [
'error' => [
'code' => 'no_front_page',
'message' => esc_html__( 'show_on_front is set to "page" but no front page is assigned (page_on_front is empty). Assign a static front page under WP Dashboard > Settings > Reading.', 'seo-by-rank-math' ),
],
];
}
$updated = [];
if ( isset( $input['title'] ) ) {
update_post_meta( $page_id, 'rank_math_title', sanitize_text_field( $input['title'] ) );
$updated[] = 'title';
}
if ( isset( $input['description'] ) ) {
update_post_meta( $page_id, 'rank_math_description', sanitize_textarea_field( $input['description'] ) );
$updated[] = 'description';
}
if ( isset( $input['focus_keyword'] ) ) {
update_post_meta( $page_id, 'rank_math_focus_keyword', sanitize_text_field( $input['focus_keyword'] ) );
$updated[] = 'focus_keyword';
}
rank_math()->tracking->track_ability_executed(
'Homepage SEO Updated',
[
'homepage_type' => 'static_page',
'page_id' => $page_id,
'fields_updated' => $updated,
],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $updated,
];
}
/**
* Write title/description into the Titles & Meta settings for the
* latest-posts homepage.
*
* @param array $input Ability input.
* @return array
*/
private function update_latest_posts( array $input ): array {
$titles = $this->get_titles_option();
$updated = [];
if ( isset( $input['title'] ) ) {
$titles['homepage_title'] = sanitize_text_field( $input['title'] );
$updated[] = 'title';
}
if ( isset( $input['description'] ) ) {
$titles['homepage_description'] = sanitize_textarea_field( $input['description'] );
$updated[] = 'description';
}
$this->save_and_reset( null, $titles, null );
rank_math()->tracking->track_ability_executed(
'Homepage SEO Updated',
[
'homepage_type' => 'latest_posts',
'fields_updated' => $updated,
],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $updated,
];
}
}
@@ -0,0 +1,137 @@
<?php
/**
* Ability: rank-math/set-link-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-link-settings ability.
*/
class Set_Link_Settings extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_general' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-link-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set link settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates site-wide link behavior: nofollow for external and image links, opening external links in a new tab, nofollow domain allow/exclude lists, category base stripping, and attachment page redirects. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'nofollow_external_links' => [
'type' => 'boolean',
'title' => esc_html__( 'Nofollow External Links', 'seo-by-rank-math' ),
'description' => esc_html__( 'Automatically add rel="nofollow" to external links in content.', 'seo-by-rank-math' ),
],
'new_window_external_links' => [
'type' => 'boolean',
'title' => esc_html__( 'Open External Links in New Tab/Window', 'seo-by-rank-math' ),
'description' => esc_html__( 'Automatically add target="_blank" to external links in content.', 'seo-by-rank-math' ),
],
'nofollow_image_links' => [
'type' => 'boolean',
'title' => esc_html__( 'Nofollow Image File Links', 'seo-by-rank-math' ),
'description' => esc_html__( 'Automatically add rel="nofollow" to links pointing to external image files.', 'seo-by-rank-math' ),
],
'nofollow_domains' => [
'type' => 'string',
'title' => esc_html__( 'Nofollow Domains', 'seo-by-rank-math' ),
'description' => esc_html__( 'Newline-separated list of domains to nofollow. If empty, nofollow applies to all external domains (when enabled). Only takes effect when nofollow_external_links or nofollow_image_links is also enabled — hidden in the UI otherwise.', 'seo-by-rank-math' ),
],
'nofollow_exclude_domains' => [
'type' => 'string',
'title' => esc_html__( 'Nofollow Exclude Domains', 'seo-by-rank-math' ),
'description' => esc_html__( 'Newline-separated list of domains to exclude from nofollow. Only takes effect when nofollow_external_links or nofollow_image_links is also enabled — hidden in the UI otherwise.', 'seo-by-rank-math' ),
],
'strip_category_base' => [
'type' => 'boolean',
'title' => esc_html__( 'Strip Category Base', 'seo-by-rank-math' ),
'description' => esc_html__( 'Remove /category/ from category archive URLs.', 'seo-by-rank-math' ),
],
'attachment_redirect_urls' => [
'type' => 'boolean',
'title' => esc_html__( 'Redirect Attachments', 'seo-by-rank-math' ),
'description' => esc_html__( 'Redirect attachment page URLs to the post they appear in.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$general = $this->get_general_option();
$this->apply_toggle_fields(
$general,
$input,
[
'nofollow_external_links',
'new_window_external_links',
'nofollow_image_links',
'strip_category_base',
'attachment_redirect_urls',
]
);
foreach ( [ 'nofollow_domains', 'nofollow_exclude_domains' ] as $field ) {
if ( isset( $input[ $field ] ) ) {
$general[ $field ] = sanitize_textarea_field( $input[ $field ] );
}
}
$this->save_and_reset( $general, null, null );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Link Settings Updated',
[ 'fields_updated' => $keys ],
'rank_math_general'
);
return [
'saved' => true,
'updated' => $keys,
];
}
}
@@ -0,0 +1,179 @@
<?php
/**
* Ability: rank-math/set-module-status
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-module-status ability.
*/
class Set_Module_Status extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'manage_options' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-module-status',
[
'category' => $this->category,
'label' => esc_html__( 'Set module status', 'seo-by-rank-math' ),
'description' => esc_html__(
'Enables or disables Rank Math modules (e.g. sitemap, redirections, 404-monitor, rich-snippet). Only provided module slugs are changed; omitted modules keep their current state. Modules with unmet dependencies (e.g. Video Sitemap requires Sitemap and Schema) cannot be enabled until their dependencies are active or enabled in the same call. Modules whose external requirements are not met (e.g. WooCommerce module without the WooCommerce plugin active) cannot be enabled at all.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'modules' ],
'properties' => [
'modules' => [
'type' => 'object',
'title' => esc_html__( 'Modules', 'seo-by-rank-math' ),
'description' => esc_html__( 'Map of module slug to desired active state. Call get-settings first to see the full list of registered module slugs and their current status.', 'seo-by-rank-math' ),
'additionalProperties' => [ 'type' => 'boolean' ],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true, 'List of module slugs whose status was changed.' ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$requested = isset( $input['modules'] ) && is_array( $input['modules'] ) ? $input['modules'] : [];
if ( empty( $requested ) ) {
return [
'error' => [
'code' => 'missing_modules',
'message' => esc_html__( 'modules must be a non-empty map of module slug to boolean.', 'seo-by-rank-math' ),
],
];
}
$registered = $this->get_registered_modules();
$active = $this->get_active_modules();
$to_update = [];
foreach ( $requested as $slug => $enable ) {
if ( ! array_key_exists( $slug, $registered ) ) {
return [
'error' => [
'code' => 'invalid_module',
'message' => sprintf(
/* translators: module slug */
esc_html__( 'Unknown module: %s', 'seo-by-rank-math' ),
esc_html( $slug )
),
],
];
}
if ( $enable ) {
if ( $registered[ $slug ]->is_disabled() ) {
$disabled_text = $registered[ $slug ]->get( 'disabled_text' );
if ( empty( $disabled_text ) ) {
$disabled_text = sprintf(
/* translators: module slug */
esc_html__( 'Cannot enable "%s" — its requirements are not met.', 'seo-by-rank-math' ),
esc_html( $slug )
);
}
return [
'error' => [
'code' => 'module_disabled',
'message' => $disabled_text,
],
];
}
foreach ( $registered[ $slug ]->get_dependencies() as $dependency ) {
$dependency_met = in_array( $dependency, $active, true )
|| ( isset( $requested[ $dependency ] ) && $requested[ $dependency ] );
if ( ! $dependency_met ) {
return [
'error' => [
'code' => 'unmet_dependency',
'message' => sprintf(
/* translators: 1: module slug, 2: required module slug */
esc_html__( 'Cannot enable "%1$s" — it requires the "%2$s" module to be active or enabled in the same call.', 'seo-by-rank-math' ),
esc_html( $slug ),
esc_html( $dependency )
),
],
];
}
}
}
$to_update[ $slug ] = $enable ? 'on' : 'off';
}
Helper::update_modules( $to_update );
foreach ( $to_update as $slug => $state ) {
if ( 'off' === $state && in_array( $slug, [ 'sitemap', 'llms-txt' ], true ) ) {
delete_option( 'rewrite_rules' );
}
do_action( 'rank_math/module_changed', $slug, $state );
}
$keys = array_keys( $requested );
rank_math()->tracking->track_ability_executed(
'Module Status Updated',
[ 'modules_updated' => $keys ],
'manage_options'
);
return [
'saved' => true,
'updated' => $keys,
];
}
/**
* Registered modules keyed by slug. Extracted for testability.
*
* @return array<string, \RankMath\Module\Module>
*/
protected function get_registered_modules(): array {
return rank_math()->manager->modules;
}
}
@@ -0,0 +1,90 @@
<?php
/**
* Ability: rank-math/set-plugin-preferences
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-plugin-preferences ability.
*/
class Set_Plugin_Preferences extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'manage_options' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-plugin-preferences',
[
'category' => $this->category,
'label' => esc_html__( 'Set plugin preferences', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates Rank Math plugin-level preferences that are not part of a settings section. Currently supports toggling automatic plugin updates.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'enable_auto_update' ],
'properties' => [
'enable_auto_update' => [
'type' => 'boolean',
'title' => esc_html__( 'Enable Automatic Updates', 'seo-by-rank-math' ),
'description' => esc_html__( 'Whether WordPress should automatically install new Rank Math plugin updates.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$enable = ! empty( $input['enable_auto_update'] );
Helper::toggle_auto_update_setting( $enable ? 'on' : 'off' );
rank_math()->tracking->track_ability_executed(
'Plugin Preferences Updated',
[ 'enable_auto_update' => $enable ],
'manage_options'
);
return [
'saved' => true,
'updated' => [ 'enable_auto_update' ],
];
}
}
@@ -0,0 +1,224 @@
<?php
/**
* Ability: rank-math/set-post-type-seo-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-post-type-seo-settings ability.
*/
class Set_Post_Type_Seo_Settings extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_titles' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-post-type-seo-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set post type SEO settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates per-post-type SEO defaults: default title/description templates, default Schema type, default article type, custom robots meta, and whether to show SEO controls on the editor screen. Accepts a map keyed by post type slug; only provided post types and fields are changed.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'post_types' ],
'properties' => [
'post_types' => [
'type' => 'object',
'title' => esc_html__( 'Post Types', 'seo-by-rank-math' ),
'description' => esc_html__( 'Map of post type slug to its SEO settings. Call get-settings first to see registered post type slugs.', 'seo-by-rank-math' ),
'additionalProperties' => [
'type' => 'object',
'properties' => [
'title' => [
'type' => 'string',
'title' => esc_html__( 'Single Title', 'seo-by-rank-math' ),
'description' => esc_html__( 'Default title tag for single pages of this post type. Supports Rank Math title variables.', 'seo-by-rank-math' ),
],
'description' => [
'type' => 'string',
'title' => esc_html__( 'Single Description', 'seo-by-rank-math' ),
'description' => esc_html__( 'Default meta description for single pages of this post type. Supports Rank Math variables.', 'seo-by-rank-math' ),
],
'default_rich_snippet' => [
'type' => 'string',
'title' => esc_html__( 'Schema Type', 'seo-by-rank-math' ),
'description' => esc_html__( 'Default Schema type slug for new posts of this type (e.g. "off", "article", "product", "event"). Call get-settings first or see the Schema Type list in WP Admin for valid values — the list varies per post type and active modules.', 'seo-by-rank-math' ),
],
'default_article_type' => [
'type' => 'string',
'enum' => [ 'Article', 'BlogPosting', 'NewsArticle' ],
'title' => esc_html__( 'Article Type', 'seo-by-rank-math' ),
'description' => esc_html__( 'Default article schema sub-type. Only used when default_rich_snippet is "article".', 'seo-by-rank-math' ),
],
'custom_robots' => [
'type' => 'boolean',
'title' => esc_html__( 'Custom Robots Meta', 'seo-by-rank-math' ),
'description' => esc_html__( 'Whether to use custom robots meta values for this post type instead of the Global Meta default.', 'seo-by-rank-math' ),
],
'robots' => [
'type' => 'array',
'items' => [
'type' => 'string',
'enum' => self::ROBOTS_DIRECTIVES,
],
'title' => esc_html__( 'Robots Meta', 'seo-by-rank-math' ),
'description' => esc_html__( 'Custom robots meta values for this post type. Only takes effect when custom_robots is enabled.', 'seo-by-rank-math' ),
],
'add_meta_box' => [
'type' => 'boolean',
'title' => esc_html__( 'Add SEO Controls', 'seo-by-rank-math' ),
'description' => esc_html__( 'Whether to add SEO controls to the editor screen for posts of this type.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true, 'List of "post_type.field" identifiers that were updated.' ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_types = isset( $input['post_types'] ) && is_array( $input['post_types'] ) ? $input['post_types'] : [];
if ( empty( $post_types ) ) {
return [
'error' => [
'code' => 'missing_post_types',
'message' => esc_html__( 'post_types must be a non-empty map of post type slug to settings.', 'seo-by-rank-math' ),
],
];
}
$accessible = $this->get_accessible_post_types();
foreach ( $post_types as $post_type => $fields ) {
if ( ! in_array( $post_type, $accessible, true ) ) {
return [
'error' => [
'code' => 'invalid_post_type',
'message' => sprintf(
/* translators: post type slug */
esc_html__( 'Unknown or inaccessible post type: %s', 'seo-by-rank-math' ),
esc_html( $post_type )
),
],
];
}
if ( isset( $fields['robots'] ) ) {
foreach ( (array) $fields['robots'] as $value ) {
if ( ! in_array( $value, self::ROBOTS_DIRECTIVES, true ) ) {
return [
'error' => [
'code' => 'invalid_robots',
'message' => esc_html__( 'robots may only contain: index, noindex, nofollow, noarchive, noimageindex, nosnippet.', 'seo-by-rank-math' ),
],
];
}
}
}
if ( isset( $fields['default_article_type'] ) && ! in_array( $fields['default_article_type'], [ 'Article', 'BlogPosting', 'NewsArticle' ], true ) ) {
return [
'error' => [
'code' => 'invalid_article_type',
'message' => esc_html__( 'default_article_type must be one of: Article, BlogPosting, NewsArticle.', 'seo-by-rank-math' ),
],
];
}
}
$titles = $this->get_titles_option();
$updated = [];
foreach ( $post_types as $post_type => $fields ) {
$prefix = "pt_{$post_type}_";
foreach ( [ 'title', 'description' ] as $field ) {
if ( isset( $fields[ $field ] ) ) {
$titles[ $prefix . $field ] = sanitize_text_field( $fields[ $field ] );
$updated[] = "{$post_type}.{$field}";
}
}
if ( isset( $fields['default_rich_snippet'] ) ) {
$titles[ $prefix . 'default_rich_snippet' ] = sanitize_text_field( $fields['default_rich_snippet'] );
$updated[] = "{$post_type}.default_rich_snippet";
}
if ( isset( $fields['default_article_type'] ) ) {
$titles[ $prefix . 'default_article_type' ] = $fields['default_article_type'];
$updated[] = "{$post_type}.default_article_type";
}
if ( isset( $fields['custom_robots'] ) ) {
$titles[ $prefix . 'custom_robots' ] = $fields['custom_robots'] ? 'on' : 'off';
$updated[] = "{$post_type}.custom_robots";
}
if ( isset( $fields['robots'] ) ) {
$titles[ $prefix . 'robots' ] = array_map( 'sanitize_text_field', (array) $fields['robots'] );
$updated[] = "{$post_type}.robots";
}
if ( isset( $fields['add_meta_box'] ) ) {
$titles[ $prefix . 'add_meta_box' ] = $fields['add_meta_box'] ? 'on' : 'off';
$updated[] = "{$post_type}.add_meta_box";
}
}
$this->save_and_reset( null, $titles, null );
rank_math()->tracking->track_ability_executed(
'Post Type SEO Settings Updated',
[
'post_types' => array_keys( $post_types ),
'fields_updated' => $updated,
],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $updated,
];
}
}
@@ -0,0 +1,219 @@
<?php
/**
* Ability: rank-math/set-sitemap-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-sitemap-settings ability.
*/
class Set_Sitemap_Settings extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_sitemap' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-sitemap-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set sitemap settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates XML sitemap settings: links per sitemap page, image inclusion, excluded post/term IDs, author archive inclusion, and per-post-type/per-taxonomy sitemap inclusion. All fields are optional — omitted fields keep their current stored value. Requires the sitemap module to be active; enable it first with set-module-status if needed.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'items_per_page' => [
'type' => 'integer',
'title' => esc_html__( 'Links Per Sitemap', 'seo-by-rank-math' ),
'description' => esc_html__( 'Max number of links on each sitemap page.', 'seo-by-rank-math' ),
],
'include_images' => [
'type' => 'boolean',
'title' => esc_html__( 'Images in Sitemaps', 'seo-by-rank-math' ),
'description' => esc_html__( 'Include reference to images from the post content in sitemaps.', 'seo-by-rank-math' ),
],
'include_featured_image' => [
'type' => 'boolean',
'title' => esc_html__( 'Include Featured Images', 'seo-by-rank-math' ),
'description' => esc_html__( 'Include the Featured Image too, even if it does not appear directly in the post content. Only takes effect when include_images is also enabled.', 'seo-by-rank-math' ),
],
'exclude_posts' => [
'type' => 'string',
'title' => esc_html__( 'Exclude Posts', 'seo-by-rank-math' ),
'description' => esc_html__( 'Comma-separated post IDs to exclude from the sitemap. Applies to all post types.', 'seo-by-rank-math' ),
],
'exclude_terms' => [
'type' => 'string',
'title' => esc_html__( 'Exclude Terms', 'seo-by-rank-math' ),
'description' => esc_html__( 'Comma-separated term IDs to exclude from the sitemap. Applies to all taxonomies.', 'seo-by-rank-math' ),
],
'authors_sitemap' => [
'type' => 'boolean',
'title' => esc_html__( 'Include Authors in Sitemap', 'seo-by-rank-math' ),
'description' => esc_html__( 'Include author archives in the XML sitemap.', 'seo-by-rank-math' ),
],
'post_types' => [
'type' => 'object',
'title' => esc_html__( 'Post Types', 'seo-by-rank-math' ),
'description' => esc_html__( 'Map of post type slug to whether it should be included in the XML sitemap. Call get-settings first to see registered post type sitemap status.', 'seo-by-rank-math' ),
'additionalProperties' => [ 'type' => 'boolean' ],
],
'taxonomies' => [
'type' => 'object',
'title' => esc_html__( 'Taxonomies', 'seo-by-rank-math' ),
'description' => esc_html__( 'Map of taxonomy slug to whether it should be included in the XML sitemap.', 'seo-by-rank-math' ),
'additionalProperties' => [ 'type' => 'boolean' ],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true, 'List of top-level field names that were updated.' ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
if ( isset( $input['post_types'] ) ) {
$accessible_post_types = $this->get_accessible_post_types();
foreach ( array_keys( $input['post_types'] ) as $post_type ) {
if ( ! in_array( $post_type, $accessible_post_types, true ) ) {
return [
'error' => [
'code' => 'invalid_post_type',
'message' => sprintf(
/* translators: post type slug */
esc_html__( 'Unknown or inaccessible post type: %s', 'seo-by-rank-math' ),
esc_html( $post_type )
),
],
];
}
}
}
if ( isset( $input['taxonomies'] ) ) {
$accessible_taxonomies = $this->get_accessible_taxonomies();
foreach ( array_keys( $input['taxonomies'] ) as $taxonomy ) {
if ( ! in_array( $taxonomy, $accessible_taxonomies, true ) ) {
return [
'error' => [
'code' => 'invalid_taxonomy',
'message' => sprintf(
/* translators: taxonomy slug */
esc_html__( 'Unknown or inaccessible taxonomy: %s', 'seo-by-rank-math' ),
esc_html( $taxonomy )
),
],
];
}
}
}
$sitemap = $this->get_sitemap_option();
if ( isset( $input['items_per_page'] ) ) {
$sitemap['items_per_page'] = (string) absint( $input['items_per_page'] );
}
$this->apply_toggle_fields(
$sitemap,
$input,
[ 'include_images', 'include_featured_image', 'authors_sitemap' ]
);
foreach ( [ 'exclude_posts', 'exclude_terms' ] as $field ) {
if ( isset( $input[ $field ] ) ) {
$sitemap[ $field ] = sanitize_text_field( $input[ $field ] );
}
}
if ( isset( $input['post_types'] ) ) {
foreach ( $input['post_types'] as $post_type => $enabled ) {
$sitemap[ "pt_{$post_type}_sitemap" ] = $enabled ? 'on' : 'off';
}
}
if ( isset( $input['taxonomies'] ) ) {
foreach ( $input['taxonomies'] as $taxonomy => $enabled ) {
$sitemap[ "tax_{$taxonomy}_sitemap" ] = $enabled ? 'on' : 'off';
}
}
$this->save_and_reset( null, null, $sitemap );
/**
* Fires after set-sitemap-settings saves its FREE fields, so PRO can persist
* its own sitemap fields (news_sitemap_publication_name, video_sitemap_post_type,
* hide_video_sitemap, local_sitemap) from the same input.
*
* @param array $input Raw ability input.
*/
do_action( 'rank_math/abilities/set_sitemap_settings/after_save', $input );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Sitemap Settings Updated',
[ 'fields_updated' => $keys ],
'rank_math_sitemap'
);
return [
'saved' => true,
'updated' => $keys,
];
}
/**
* Current raw sitemap option. Extracted for testability.
*
* @return array
*/
protected function get_sitemap_option(): array {
return (array) get_option( 'rank-math-options-sitemap', [] );
}
/**
* Accessible taxonomy slugs. Extracted for testability.
*
* @return array<int, string>
*/
protected function get_accessible_taxonomies(): array {
return array_keys( Helper::get_accessible_taxonomies() );
}
}
@@ -0,0 +1,161 @@
<?php
/**
* Ability: rank-math/set-website-identity
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-website-identity ability.
*/
class Set_Website_Identity extends Abstract_Ability {
/**
* Allowed values for the knowledgegraph_type field.
*/
const KNOWLEDGEGRAPH_TYPES = [ 'person', 'company' ];
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_titles' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-website-identity',
[
'category' => $this->category,
'label' => esc_html__( 'Set website identity', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates the site\'s Knowledge Graph identity used by Rank Math for schema and social markup: knowledge graph type (person/company), website name, alternate name, knowledge graph name, organization description, business type, and site URL override. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'knowledgegraph_type' => [
'type' => 'string',
'enum' => self::KNOWLEDGEGRAPH_TYPES,
'description' => esc_html__( 'Whether the site represents a person or a company/organization.', 'seo-by-rank-math' ),
],
'website_name' => [
'type' => 'string',
'description' => esc_html__( 'The website name used in schema and social markup.', 'seo-by-rank-math' ),
],
'website_alternate_name' => [
'type' => 'string',
'description' => esc_html__( 'An alternate name for the website.', 'seo-by-rank-math' ),
],
'knowledgegraph_name' => [
'type' => 'string',
'description' => esc_html__( 'The person or organization name used in the Knowledge Graph.', 'seo-by-rank-math' ),
],
'organization_description' => [
'type' => 'string',
'description' => esc_html__( 'Description of the organization. Only used when knowledgegraph_type is "company".', 'seo-by-rank-math' ),
],
'local_business_type' => [
'type' => 'string',
'description' => esc_html__( 'Schema.org business type slug (e.g. "Restaurant", "LegalService", "Organization"), spaces removed. Only used when knowledgegraph_type is "company". Call get-settings first or see the Local SEO business type list in WP Admin for valid values.', 'seo-by-rank-math' ),
],
'url' => [
'type' => 'string',
'description' => esc_html__( 'Site URL override used in Knowledge Graph markup.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
if ( isset( $input['knowledgegraph_type'] ) && ! in_array( $input['knowledgegraph_type'], self::KNOWLEDGEGRAPH_TYPES, true ) ) {
return [
'error' => [
'code' => 'invalid_knowledgegraph_type',
'message' => esc_html__( 'knowledgegraph_type must be either "person" or "company".', 'seo-by-rank-math' ),
],
];
}
if ( isset( $input['local_business_type'] ) && ! array_key_exists( $input['local_business_type'], $this->get_business_types() ) ) {
return [
'error' => [
'code' => 'invalid_local_business_type',
'message' => esc_html__( 'local_business_type is not a recognized Schema.org business type slug.', 'seo-by-rank-math' ),
],
];
}
$titles = $this->get_titles_option();
foreach ( [ 'knowledgegraph_type', 'website_name', 'website_alternate_name', 'knowledgegraph_name', 'local_business_type' ] as $field ) {
if ( isset( $input[ $field ] ) ) {
$titles[ $field ] = sanitize_text_field( $input[ $field ] );
}
}
if ( isset( $input['url'] ) ) {
$titles['url'] = esc_url_raw( $input['url'] );
}
if ( isset( $input['organization_description'] ) ) {
$titles['organization_description'] = wp_kses_post( $input['organization_description'] );
}
$this->save_and_reset( null, $titles, null );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Website Identity Updated',
[ 'fields_updated' => $keys ],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $keys,
];
}
/**
* Valid Schema.org business type slugs. Extracted for testability.
*
* @return array<string, string>
*/
protected function get_business_types(): array {
return Helper::choices_business_types();
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Subscriber for Settings abilities.
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Settings ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Settings abilities.
*/
const CATEGORY_SLUG = 'rank-math-settings';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_abilities' );
}
/**
* Register the Settings ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Settings', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to read and configure Rank Math plugin settings.', 'seo-by-rank-math' ),
]
);
}
/**
* Register all Settings abilities.
*
* @return void
*/
public function register_abilities(): void {
$classes = [
Get_Settings::class,
Get_System_Status::class,
Get_Llms_Txt::class,
Get_Robots_Txt::class,
Set_Website_Identity::class,
Set_Global_Seo_Settings::class,
Set_Homepage_Seo::class,
Set_Link_Settings::class,
Set_Module_Status::class,
Set_Sitemap_Settings::class,
Set_Plugin_Preferences::class,
Set_Post_Type_Seo_Settings::class,
Set_Breadcrumb_Settings::class,
];
foreach ( $classes as $class ) {
( new $class( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,335 @@
<?php
/**
* Ability: rank-math/get-sitemap-status
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Sitemap
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Sitemap;
use RankMath\Abilities\Ability_Interface;
use RankMath\Helper;
use RankMath\Sitemap\Generator;
use RankMath\Sitemap\Router;
use RankMath\Sitemap\Sitemap;
use RankMath\Sitemap\Providers\Post_Type as Post_Type_Provider;
use RankMath\Sitemap\Providers\Taxonomy as Taxonomy_Provider;
use RankMath\Sitemap\Providers\Author as Author_Provider;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-sitemap-status ability.
*/
class Get_Sitemap_Status implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-sitemap-status',
[
'category' => $this->category,
'label' => esc_html__( 'Get sitemap status', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns whether the XML sitemap is enabled, the sitemap index URL, and the active sitemap types (post types, taxonomies, and the Local SEO sitemap, when active) with their URLs and estimated entry counts.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_sitemap' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$enabled = Helper::is_module_active( 'sitemap' );
$result = [
'enabled' => $enabled,
'index_url' => Router::get_base_url( Sitemap::get_sitemap_index_slug() . '.xml' ),
'sitemaps' => $this->get_sitemaps(),
];
rank_math()->tracking->track_ability_executed(
'Sitemap Status Fetched',
[
'enabled' => $enabled,
'sitemaps_count' => count( $result['sitemaps'] ),
],
'rank_math_sitemap'
);
return $result;
}
/**
* Build the list of active sitemap types with their URL and estimated entry count.
*
* Reuses the real Generator's provider list, so PRO types (e.g. news/video)
* show up automatically. Local SEO's `local-sitemap.xml` isn't a Provider
* though, so it's captured separately via get_non_provider_entries().
*
* @return array
*/
private function get_sitemaps(): array {
$max_entries = absint( Helper::get_settings( 'sitemap.items_per_page', 100 ) );
$providers = ( new Generator() )->providers;
$sitemaps = [];
foreach ( $providers as $provider ) {
$sitemaps = array_merge( $sitemaps, $this->build_sitemap_entries( $provider, $max_entries ) );
}
$local_sitemap = $this->get_local_sitemap();
if ( null !== $local_sitemap ) {
$sitemaps[] = $local_sitemap;
}
return array_merge( $sitemaps, $this->get_non_provider_entries() );
}
/**
* Capture sitemap entries added outside the Provider system, via the
* `rank_math/sitemap/index` filter (currently only Local SEO's KML_File).
*
* The 'local' type is excluded here because get_local_sitemap() already
* builds that entry with an accurate location count; KML_File::add_local_sitemap()
* fires this same filter internally, so without the exclusion the local
* sitemap would be added twice.
*
* @return array
*/
private function get_non_provider_entries(): array {
$entries = [];
$capture = function ( $item, $label, $type_slug = null ) use ( &$entries ) {
$type = ( is_string( $type_slug ) && '' !== $type_slug ) ? $type_slug : $label;
if ( ! empty( $item['loc'] ) && 'local' !== $type ) {
$entries[] = [
'type' => $type,
'url' => $item['loc'],
'estimated_count' => 1,
];
}
return $item;
};
add_filter( 'rank_math/sitemap/index/entry', $capture, 10, 3 );
apply_filters( 'rank_math/sitemap/index', '' );
remove_filter( 'rank_math/sitemap/index/entry', $capture, 10 );
return $entries;
}
/**
* Build sitemap entries for a single provider.
*
* Get_index_links() only returns {loc, lastmod}, so type and page number
* are captured via the `sitemap/index/entry` filter it fires internally.
* Per-page counts use each provider's own safe public method instead of
* get_sitemap_links(), which can die() via Sitemap::maybe_redirect() when
* called outside an actual sitemap page request.
*
* @param object $provider Sitemap provider instance.
* @param int $max_entries Entries per sitemap page.
* @return array
*/
private function build_sitemap_entries( $provider, int $max_entries ): array {
$entries = [];
$capture = function ( $item, $label, $type_slug = null ) use ( &$entries ) {
if ( ! empty( $item['loc'] ) ) {
$entries[] = [
'type' => ( is_string( $type_slug ) && '' !== $type_slug ) ? $type_slug : $label,
'url' => $item['loc'],
];
}
return $item;
};
add_filter( 'rank_math/sitemap/index/entry', $capture, 10, 3 );
$provider->get_index_links( $max_entries );
remove_filter( 'rank_math/sitemap/index/entry', $capture, 10 );
$post_type_totals = [];
$page_numbers = [];
$sitemaps = [];
foreach ( $entries as $entry ) {
$type = $entry['type'];
$page_numbers[ $type ] = ( $page_numbers[ $type ] ?? 0 ) + 1;
$page = $page_numbers[ $type ];
if ( $provider instanceof Post_Type_Provider ) {
if ( ! isset( $post_type_totals[ $type ] ) ) {
$post_type_totals[ $type ] = (int) $provider->get_post_type_count( $type );
}
$offset = ( $page - 1 ) * $max_entries;
$estimated_count = max( 0, min( $max_entries, $post_type_totals[ $type ] - $offset ) );
} elseif ( $provider instanceof Taxonomy_Provider ) {
$estimated_count = $this->count_taxonomy_page( $provider, $type, $max_entries, $page );
} elseif ( $provider instanceof Author_Provider ) {
$estimated_count = count(
(array) $provider->get_users(
[
'offset' => ( $page - 1 ) * $max_entries,
'number' => $max_entries,
]
)
);
} else {
$estimated_count = $max_entries;
}
$sitemaps[] = [
'type' => $type,
'url' => $entry['url'],
'estimated_count' => $estimated_count,
];
}
return $sitemaps;
}
/**
* Build the Local SEO sitemap entry, if the Local Sitemap is active.
*
* Mirrors the conditions in RankMath\Local_Seo\Local_Seo::location_sitemap(),
* which is what actually decides whether local-sitemap.xml gets served.
*
* @return array|null
*/
private function get_local_sitemap(): ?array {
if (
! Helper::is_module_active( 'sitemap' ) ||
! Helper::is_module_active( 'local-seo' ) ||
'company' !== Helper::get_settings( 'titles.knowledgegraph_type' ) ||
! apply_filters( 'rank_math/sitemap/locations', false ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
) {
return null;
}
$locations = apply_filters( // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
'rank_math/sitemap/locations/data',
[ [ 'name' => Helper::get_settings( 'titles.knowledgegraph_name' ) ] ]
);
return [
'type' => 'local',
'url' => Router::get_base_url( 'local-sitemap.xml' ),
'estimated_count' => is_array( $locations ) ? count( $locations ) : 0,
];
}
/**
* Real per-page term count for a taxonomy, via Taxonomy_Provider::get_terms().
*
* @param Taxonomy_Provider $provider Taxonomy provider instance.
* @param string $taxonomy Taxonomy slug.
* @param int $max_entries Entries per sitemap page.
* @param int $current_page Page number (1-indexed).
* @return int
*/
private function count_taxonomy_page( Taxonomy_Provider $provider, string $taxonomy, int $max_entries, int $current_page ): int {
$taxonomy_object = get_taxonomy( $taxonomy );
if ( ! $taxonomy_object ) {
return 0;
}
return count( (array) $provider->get_terms( $taxonomy_object, $max_entries, $current_page ) );
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'enabled' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether the XML sitemap module is active.', 'seo-by-rank-math' ),
],
'index_url' => [
'type' => 'string',
'description' => esc_html__( 'The URL of the sitemap index file.', 'seo-by-rank-math' ),
],
'sitemaps' => [
'type' => 'array',
'description' => esc_html__( 'The active sitemap types, e.g. post types, taxonomies, and the Local SEO sitemap (PRO adds news/video when active).', 'seo-by-rank-math' ),
'items' => [
'type' => 'object',
'properties' => [
'type' => [ 'type' => 'string' ],
'url' => [ 'type' => 'string' ],
'estimated_count' => [ 'type' => 'integer' ],
],
],
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Sitemap abilities.
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Sitemap
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Sitemap;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Sitemap ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Sitemap abilities.
*/
const CATEGORY_SLUG = 'rank-math-sitemap';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_sitemap_status' );
}
/**
* Register the Sitemap ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Sitemap', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to inspect the XML sitemap status.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-sitemap-status ability.
*
* @return void
*/
public function register_get_sitemap_status(): void {
( new Get_Sitemap_Status( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.