Actualizacion 7.1.2
This commit is contained in:
+72
-5
@@ -12,6 +12,7 @@ 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;
|
||||
@@ -66,14 +67,18 @@ class Create_AI_Visibility_Brand implements Ability_Interface {
|
||||
[
|
||||
'category' => $this->category,
|
||||
'label' => esc_html__( 'Create AI Visibility brand', 'seo-by-rank-math' ),
|
||||
'description' => esc_html__(
|
||||
'Creates a new brand for AI Visibility monitoring, triggering an initial analysis automatically.',
|
||||
'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' ],
|
||||
'required' => [ 'name', 'url', 'language', 'platforms' ],
|
||||
'properties' => [
|
||||
'name' => [
|
||||
'type' => 'string',
|
||||
@@ -94,6 +99,30 @@ class Create_AI_Visibility_Brand implements Ability_Interface {
|
||||
'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,
|
||||
],
|
||||
@@ -130,11 +159,19 @@ class Create_AI_Visibility_Brand implements Ability_Interface {
|
||||
* @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 );
|
||||
|
||||
@@ -149,11 +186,28 @@ class Create_AI_Visibility_Brand implements Ability_Interface {
|
||||
'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.
|
||||
*
|
||||
@@ -176,6 +230,19 @@ class Create_AI_Visibility_Brand implements Ability_Interface {
|
||||
'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' ],
|
||||
@@ -188,7 +255,7 @@ class Create_AI_Visibility_Brand implements Ability_Interface {
|
||||
],
|
||||
'error' => [
|
||||
'type' => 'string',
|
||||
'description' => 'Present only on failure — human-readable error from the upstream API.',
|
||||
'description' => 'Present only on failure — human-readable error from validation or the upstream API.',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
+36
-26
@@ -109,7 +109,6 @@ class Get_AI_Visibility_Brand_Insights implements Ability_Interface {
|
||||
|
||||
$cached = Cache::get_analysis( $brand_id );
|
||||
|
||||
// Cache miss or stale — signal the caller to trigger a fetch via the REST endpoint.
|
||||
if ( false === $cached || Cache::is_brand_stale( $brand_id ) ) {
|
||||
rank_math()->tracking->track_ability_executed(
|
||||
'AI Visibility Brand Insights Fetched',
|
||||
@@ -175,31 +174,38 @@ class Get_AI_Visibility_Brand_Insights implements Ability_Interface {
|
||||
'type' => [ 'number', 'null' ],
|
||||
'description' => 'Total number of AI citations.',
|
||||
],
|
||||
'analysis' => [
|
||||
'type' => [ 'object', 'null' ],
|
||||
'description' => 'Metadata about the latest analysis run.',
|
||||
'properties' => [
|
||||
'id' => [
|
||||
'type' => [ 'string', 'null' ],
|
||||
'description' => 'Analysis UUID.',
|
||||
],
|
||||
'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.',
|
||||
'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.',
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
@@ -243,6 +249,10 @@ class Get_AI_Visibility_Brand_Insights implements Ability_Interface {
|
||||
'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.',
|
||||
|
||||
@@ -18,6 +18,8 @@ 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;
|
||||
@@ -74,6 +76,8 @@ class Abilities {
|
||||
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 ),
|
||||
];
|
||||
|
||||
|
||||
+13
@@ -11,6 +11,7 @@
|
||||
namespace RankMath\Abilities\Link_Genius;
|
||||
|
||||
use RankMath\Abilities\Ability_Interface;
|
||||
use RankMath\Rest\Rest_Helper;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
@@ -117,6 +118,15 @@ class Get_Post_Links implements Ability_Interface {
|
||||
*/
|
||||
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(
|
||||
[
|
||||
@@ -226,6 +236,9 @@ class Get_Post_Links implements Ability_Interface {
|
||||
],
|
||||
],
|
||||
],
|
||||
'error' => [
|
||||
'type' => 'string',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
+219
@@ -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' ],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
+79
@@ -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.
|
||||
+335
@@ -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.
|
||||
@@ -31,13 +31,14 @@ class KB {
|
||||
'free-account' => 'https://rankmath.com/my-account/',
|
||||
'support' => 'https://rankmath.com/support/',
|
||||
'pro' => 'https://rankmath.com/pricing/',
|
||||
'ai-pricing' => 'https://rankmath.com/ai/pricing/',
|
||||
'site-checkout' => 'https://rankmath.com/site-checkout/',
|
||||
'changelog' => 'https://rankmath.com/changelog/',
|
||||
'changelog-free' => 'https://rankmath.com/changelog/free/',
|
||||
'help-affiliate' => 'https://rankmath.com/affiliates/',
|
||||
'seo-care' => 'https://rankmath.com/services/',
|
||||
'content-ai' => 'https://rankmath.com/content-ai/',
|
||||
'content-ai-pricing-tables' => 'https://rankmath.com/content-ai/?#pricing-tables',
|
||||
'content-ai-pricing-tables' => 'https://rankmath.com/ai/pricing/',
|
||||
'content-ai-restore-credits' => 'https://rankmath.com/kb/how-to-restore-missing-content-ai-credits/',
|
||||
'free-vs-pro' => 'https://rankmath.com/free-vs-pro/',
|
||||
'google-updates' => 'https://rankmath.com/google-updates/',
|
||||
@@ -148,6 +149,7 @@ class KB {
|
||||
'analysis-search-console' => 'https://rankmath.com/kb/seo-analysis/?#search-console-test',
|
||||
'analysis-sitemaps' => 'https://rankmath.com/kb/seo-analysis/?#sitemaps-test',
|
||||
'analysis-auto-update' => 'https://rankmath.com/kb/seo-analysis/?#priority',
|
||||
'llms' => 'https://rankmath.com/kb/llms-txt/',
|
||||
|
||||
// Link Genius.
|
||||
'link-genius' => 'https://rankmath.com/kb/wordpress/ai-link-genius/',
|
||||
|
||||
@@ -140,9 +140,9 @@ trait Content_AI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to get Content AI Plan.
|
||||
* Function to get Rank Math AI Plan.
|
||||
*
|
||||
* @return string Content AI Plan.
|
||||
* @return string Rank Math AI Plan.
|
||||
*/
|
||||
public static function get_content_ai_plan() {
|
||||
$credits_data = get_option( self::$credits_key, [] );
|
||||
@@ -487,6 +487,140 @@ trait Content_AI {
|
||||
return ! empty( $languages ) ? current( array_keys( $languages ) ) : 'US English';
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to get the list of supported languages.
|
||||
*
|
||||
* @return array Supported languages.
|
||||
*/
|
||||
public static function get_content_ai_languages() {
|
||||
return [
|
||||
[
|
||||
'name' => 'US English',
|
||||
'icon' => '🇺🇸',
|
||||
],
|
||||
[
|
||||
'name' => 'UK English',
|
||||
'icon' => '🇬🇧',
|
||||
],
|
||||
[
|
||||
'name' => 'Arabic',
|
||||
'icon' => '🇦🇪',
|
||||
],
|
||||
[
|
||||
'name' => 'Bulgarian',
|
||||
'icon' => '🇧🇬',
|
||||
],
|
||||
[
|
||||
'name' => 'Chinese',
|
||||
'icon' => '🇨🇳',
|
||||
],
|
||||
[
|
||||
'name' => 'Czech',
|
||||
'icon' => '🇨🇿',
|
||||
],
|
||||
[
|
||||
'name' => 'Danish',
|
||||
'icon' => '🇩🇰',
|
||||
],
|
||||
[
|
||||
'name' => 'Dutch',
|
||||
'icon' => '🇳🇱',
|
||||
],
|
||||
[
|
||||
'name' => 'Estonian',
|
||||
'icon' => '🇪🇪',
|
||||
],
|
||||
[
|
||||
'name' => 'Finnish',
|
||||
'icon' => '🇫🇮',
|
||||
],
|
||||
[
|
||||
'name' => 'French',
|
||||
'icon' => '🇫🇷',
|
||||
],
|
||||
[
|
||||
'name' => 'German',
|
||||
'icon' => '🇩🇪',
|
||||
],
|
||||
[
|
||||
'name' => 'Greek',
|
||||
'icon' => '🇬🇷',
|
||||
],
|
||||
[
|
||||
'name' => 'Hebrew',
|
||||
'icon' => '🇮🇱',
|
||||
],
|
||||
[
|
||||
'name' => 'Hungarian',
|
||||
'icon' => '🇭🇺',
|
||||
],
|
||||
[
|
||||
'name' => 'Indonesian',
|
||||
'icon' => '🇮🇩',
|
||||
],
|
||||
[
|
||||
'name' => 'Italian',
|
||||
'icon' => '🇮🇹',
|
||||
],
|
||||
[
|
||||
'name' => 'Japanese',
|
||||
'icon' => '🇯🇵',
|
||||
],
|
||||
[
|
||||
'name' => 'Korean',
|
||||
'icon' => '🇰🇷',
|
||||
],
|
||||
[
|
||||
'name' => 'Latvian',
|
||||
'icon' => '🇱🇻',
|
||||
],
|
||||
[
|
||||
'name' => 'Lithuanian',
|
||||
'icon' => '🇱🇹',
|
||||
],
|
||||
[
|
||||
'name' => 'Norwegian',
|
||||
'icon' => '🇳🇴',
|
||||
],
|
||||
[
|
||||
'name' => 'Polish',
|
||||
'icon' => '🇵🇱',
|
||||
],
|
||||
[
|
||||
'name' => 'Portuguese',
|
||||
'icon' => '🇵🇹',
|
||||
],
|
||||
[
|
||||
'name' => 'Romanian',
|
||||
'icon' => '🇷🇴',
|
||||
],
|
||||
[
|
||||
'name' => 'Russian',
|
||||
'icon' => '🇷🇺',
|
||||
],
|
||||
[
|
||||
'name' => 'Slovak',
|
||||
'icon' => '🇸🇰',
|
||||
],
|
||||
[
|
||||
'name' => 'Slovenian',
|
||||
'icon' => '🇸🇮',
|
||||
],
|
||||
[
|
||||
'name' => 'Spanish',
|
||||
'icon' => '🇪🇸',
|
||||
],
|
||||
[
|
||||
'name' => 'Swedish',
|
||||
'icon' => '🇸🇪',
|
||||
],
|
||||
[
|
||||
'name' => 'Turkish',
|
||||
'icon' => '🇹🇷',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to get different error codes we get from the API
|
||||
*
|
||||
@@ -496,7 +630,7 @@ trait Content_AI {
|
||||
return [
|
||||
'not_connected' => esc_html__( 'Please connect your account to use the Content AI.', 'seo-by-rank-math' ),
|
||||
'plugin_update_required' => esc_html__( 'Please update the Rank Math SEO plugin to the latest version to use this feature.', 'seo-by-rank-math' ),
|
||||
'upgrade_required' => esc_html__( 'This feature is only available for Content AI subscribers.', 'seo-by-rank-math' ),
|
||||
'upgrade_required' => esc_html__( 'This feature is only available for Rank Math AI subscribers.', 'seo-by-rank-math' ),
|
||||
'rate_limit_exceeded' => esc_html__( 'Oops! Too many requests in a short time. Please try again after some time.', 'seo-by-rank-math' ),
|
||||
'domain_limit_reached' => esc_html__( 'You\'ve reached the monthly usage limit for this feature on your domain.', 'seo-by-rank-math' ),
|
||||
'account_limit_reached' => esc_html__( 'You\'ve reached the monthly usage limit for this feature.', 'seo-by-rank-math' ),
|
||||
|
||||
@@ -179,6 +179,55 @@ class Sitepress {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get permalink for a post, resolved in the post's own language.
|
||||
*
|
||||
* Temporarily switches WPML's active language to the post's language before
|
||||
* calling get_permalink(), then restores it. This avoids returning the wrong
|
||||
* language's URL when the active request language differs from the post's
|
||||
* language, e.g. in background/async jobs or REST/MCP requests. For
|
||||
* separate-domain installs, the scheme+host is also stripped so the caller
|
||||
* can rebuild the URL against the correct language domain.
|
||||
*
|
||||
* @param int $post_id Post ID.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_permalink( $post_id ) {
|
||||
if ( ! $this->is_active() ) {
|
||||
return get_permalink( $post_id );
|
||||
}
|
||||
|
||||
$sitepress = $this->get_var();
|
||||
|
||||
$details = apply_filters( 'wpml_post_language_details', null, $post_id );
|
||||
$code = $details['language_code'] ?? '';
|
||||
$current = $sitepress->get_current_language();
|
||||
$switched = $code && $code !== $current;
|
||||
|
||||
if ( $switched ) {
|
||||
$sitepress->switch_lang( $code, true );
|
||||
}
|
||||
|
||||
try {
|
||||
$permalink = get_permalink( $post_id );
|
||||
} finally {
|
||||
if ( $switched ) {
|
||||
$sitepress->switch_lang( $current, true );
|
||||
}
|
||||
}
|
||||
|
||||
$language_domains = $sitepress->get_setting( 'language_domains', [] );
|
||||
if ( $language_domains ) {
|
||||
$permalink = apply_filters( 'wpml_permalink', $permalink, $code );
|
||||
foreach ( $language_domains as $domain ) {
|
||||
$permalink = preg_replace( "#https?://{$domain}#i", '', $permalink );
|
||||
}
|
||||
}
|
||||
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is per domain negotiation type.
|
||||
*
|
||||
|
||||
@@ -233,12 +233,13 @@ class Manager {
|
||||
];
|
||||
|
||||
$modules['ai-visibility'] = [
|
||||
'title' => esc_html__( 'AI Visibility', 'seo-by-rank-math' ),
|
||||
'desc' => esc_html__( 'Track your brand\'s AI search visibility. Monitor brand mentions, citations, & sentiment, and discover opportunities to grow your AI visibility.', 'seo-by-rank-math' ),
|
||||
'icon' => 'ai-visibility',
|
||||
'class' => 'RankMath\AI_Visibility\AI_Visibility',
|
||||
'settings' => Helper::get_admin_url( 'ai-visibility' ),
|
||||
'betabadge' => true,
|
||||
'title' => esc_html__( 'AI Visibility', 'seo-by-rank-math' ),
|
||||
'desc' => esc_html__( 'Track your brand\'s AI search visibility. Monitor brand mentions, citations, & sentiment, and discover opportunities to grow your AI visibility.', 'seo-by-rank-math' ),
|
||||
'icon' => 'ai-visibility',
|
||||
'class' => 'RankMath\AI_Visibility\AI_Visibility',
|
||||
'settings' => Helper::get_admin_url( 'ai-visibility' ),
|
||||
'betabadge' => true,
|
||||
'upgradeable' => true,
|
||||
];
|
||||
|
||||
return $modules;
|
||||
@@ -453,7 +454,7 @@ class Manager {
|
||||
<?php } ?>
|
||||
<?php if ( $is_upgradeable && ! $is_pro_active ) { ?>
|
||||
<span class="is-upgradeable rank-math-tooltip">
|
||||
<a href="<?php KB::the( 'pro', esc_html( $module->get( 'title' ) ) . ' Module Upgradable Icon' ); ?>">
|
||||
<a href="<?php KB::the( in_array( $key, [ 'content-ai', 'ai-visibility' ], true ) ? 'ai-pricing' : 'pro', esc_html( $module->get( 'title' ) ) . ' Module Upgradable Icon' ); ?>">
|
||||
<div>«</div>
|
||||
</a>
|
||||
<span><?php echo esc_html__( 'More powerful options are available in the PRO version.', 'seo-by-rank-math' ); ?></span>
|
||||
@@ -562,7 +563,7 @@ class Manager {
|
||||
<h3><?php esc_html_e( 'Take SEO to the Next Level!', 'seo-by-rank-math' ); ?></h3>
|
||||
<ul>
|
||||
<li><?php esc_html_e( 'Unlimited personal websites', 'seo-by-rank-math' ); ?></li>
|
||||
<li><?php esc_html_e( 'Free 15-Day Content AI Trial', 'seo-by-rank-math' ); ?></li>
|
||||
<li><?php esc_html_e( 'Free 15-day Rank Math AI Trial', 'seo-by-rank-math' ); ?></li>
|
||||
<li><?php esc_html_e( 'Track 500 Keywords', 'seo-by-rank-math' ); ?></li>
|
||||
<li><?php esc_html_e( 'Powerful Schema Generator', 'seo-by-rank-math' ); ?></li>
|
||||
<li><?php esc_html_e( '24/7 Support', 'seo-by-rank-math' ); ?></li>
|
||||
|
||||
+37
@@ -15,6 +15,7 @@ use RankMath\Traits\Hooker;
|
||||
use RankMath\Admin\Page;
|
||||
use RankMath\Admin\Admin_Helper;
|
||||
use RankMath\Helpers\Param;
|
||||
use RankMath\AI_Visibility\Api\Brands_Controller;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
@@ -90,6 +91,10 @@ class Admin {
|
||||
'isSiteUrlValid' => Admin_Helper::is_site_url_valid(),
|
||||
'isPro' => defined( 'RANK_MATH_PRO_FILE' ),
|
||||
'plan' => Helper::get_content_ai_plan(),
|
||||
'languages' => Helper::get_content_ai_languages(),
|
||||
'defaultLanguage' => Helper::content_ai_default_language(),
|
||||
'platforms' => Platforms::all(),
|
||||
'maxPlatforms' => Platforms::max_selectable(),
|
||||
'locales' => array_values(
|
||||
array_filter(
|
||||
array_map(
|
||||
@@ -111,6 +116,7 @@ class Admin {
|
||||
)
|
||||
)
|
||||
),
|
||||
'intervals' => $this->get_intervals(),
|
||||
],
|
||||
],
|
||||
],
|
||||
@@ -118,6 +124,37 @@ class Admin {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the available intervals for AI Visibility.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_intervals() {
|
||||
$allowed = Brands_Controller::get_allowed_intervals();
|
||||
|
||||
$intervals = [
|
||||
[
|
||||
'label' => esc_html__( 'Daily', 'seo-by-rank-math' ),
|
||||
'value' => 'daily',
|
||||
],
|
||||
[
|
||||
'label' => esc_html__( 'Weekly', 'seo-by-rank-math' ),
|
||||
'value' => 'weekly',
|
||||
],
|
||||
[
|
||||
'label' => esc_html__( 'Monthly', 'seo-by-rank-math' ),
|
||||
'value' => 'monthly',
|
||||
],
|
||||
];
|
||||
|
||||
foreach ( $intervals as &$interval ) {
|
||||
$interval['disabled'] = ! in_array( $interval['value'], $allowed, true );
|
||||
}
|
||||
unset( $interval );
|
||||
|
||||
return $intervals;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue Mixpanel script and inject tracking data for JS events on this page.
|
||||
*/
|
||||
|
||||
+1
-1
@@ -124,7 +124,7 @@ abstract class Base_Controller extends WP_REST_Controller {
|
||||
$args['body'] = wp_json_encode( $body );
|
||||
}
|
||||
|
||||
$url = 'https://ai-visibility.rankmath.com/' . ltrim( $path, '/' );
|
||||
$url = RANK_MATH_AIV_URL . '/' . ltrim( $path, '/' );
|
||||
$response = wp_remote_request( $url, $args );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
|
||||
+207
-46
@@ -14,7 +14,9 @@ namespace RankMath\AI_Visibility\Api;
|
||||
|
||||
use WP_REST_Server;
|
||||
use WP_REST_Request;
|
||||
use RankMath\Helper;
|
||||
use RankMath\AI_Visibility\Cache;
|
||||
use RankMath\AI_Visibility\Platforms;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
@@ -28,6 +30,66 @@ class Brands_Controller extends Base_Controller {
|
||||
*/
|
||||
const BRAND_ID_PATTERN = '(?P<id>[a-zA-Z0-9\-]+)';
|
||||
|
||||
/**
|
||||
* Allowed values for the `language` request param.
|
||||
*
|
||||
* @param bool $allow_empty Whether '' (no value) is a valid choice.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_language_choices( bool $allow_empty = true ): array {
|
||||
$names = wp_list_pluck( Helper::get_content_ai_languages(), 'name' );
|
||||
return $allow_empty ? array_merge( [ '' ], $names ) : $names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allowed values for the `interval` request param.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_interval_choices(): array {
|
||||
return [ 'daily', 'weekly', 'monthly' ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cadences allowed for a given AI Visibility plan.
|
||||
*
|
||||
* @param string|null $plan Plan slug. Defaults to the current account's plan.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_allowed_intervals( ?string $plan = null ): array {
|
||||
$plan = $plan ?? Helper::get_content_ai_plan();
|
||||
|
||||
return 'expert' === $plan
|
||||
? [ 'daily', 'weekly', 'monthly' ]
|
||||
: [ 'weekly', 'monthly' ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject an `interval` value the caller's plan does not allow.
|
||||
*
|
||||
* @param string $interval Requested cadence value.
|
||||
*
|
||||
* @return \WP_Error|true
|
||||
*/
|
||||
private function check_interval_allowed( string $interval ) {
|
||||
$allowed = self::get_allowed_intervals();
|
||||
if ( in_array( $interval, $allowed, true ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->error(
|
||||
'aiv_frequency_not_allowed',
|
||||
sprintf(
|
||||
/* translators: %s: comma-separated list of allowed cadences. */
|
||||
__( 'The selected analysis frequency is not available on your plan. Allowed frequencies: %s. Upgrade your plan to unlock more frequency options.', 'seo-by-rank-math' ),
|
||||
implode( ', ', $allowed )
|
||||
),
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register routes.
|
||||
*/
|
||||
@@ -114,6 +176,23 @@ class Brands_Controller extends Base_Controller {
|
||||
'required' => false,
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'language' => [
|
||||
'description' => esc_html__( 'Output language to use when analyzing/generating content for this brand. Independent of `locale` (target country). Required; immutable after creation.', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'required' => true,
|
||||
'enum' => self::get_language_choices( false ),
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
],
|
||||
'interval' => [
|
||||
'description' => esc_html__( 'Analysis refresh cadence. Omitted → backend applies the account plan\'s default.', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'required' => false,
|
||||
'enum' => self::get_interval_choices(),
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
],
|
||||
'platforms' => Platforms::rest_arg( true ),
|
||||
],
|
||||
]
|
||||
);
|
||||
@@ -149,20 +228,33 @@ class Brands_Controller extends Base_Controller {
|
||||
'required' => false,
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'language' => [
|
||||
'type' => 'string',
|
||||
'required' => false,
|
||||
'enum' => self::get_language_choices(),
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
],
|
||||
'status' => [
|
||||
'type' => 'string',
|
||||
'required' => false,
|
||||
'enum' => [ 'active', 'inactive' ],
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'interval' => [
|
||||
'type' => 'string',
|
||||
'required' => false,
|
||||
'enum' => self::get_interval_choices(),
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
],
|
||||
'platforms' => Platforms::rest_arg( false ),
|
||||
]
|
||||
),
|
||||
]
|
||||
);
|
||||
|
||||
// GET /brands/{id}/insights — full latest-analysis payload
|
||||
// (competitors + transcripts). Cache-first; the only proxy route that
|
||||
// may call the upstream analyses/results endpoint.
|
||||
// GET /brands/{id}/insights — full latest-analysis payload (competitors + transcripts).
|
||||
register_rest_route(
|
||||
$this->namespace,
|
||||
'/brands/' . self::BRAND_ID_PATTERN . '/insights',
|
||||
@@ -244,15 +336,12 @@ class Brands_Controller extends Base_Controller {
|
||||
return $this->overview_response( $cached, false, $search );
|
||||
}
|
||||
|
||||
// Stale-while-revalidate: serve stale immediately; the client
|
||||
// fires a background `refresh=1` request on seeing `is_stale`.
|
||||
return $this->overview_response( $cached, true, $search );
|
||||
}
|
||||
|
||||
$result = $this->remote_request( 'GET', '/api/v1/overview' );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
// Serve stale cache on upstream failure rather than erroring out.
|
||||
if ( null !== $cached ) {
|
||||
return $this->overview_response( $cached, true, $search );
|
||||
}
|
||||
@@ -276,9 +365,6 @@ class Brands_Controller extends Base_Controller {
|
||||
/**
|
||||
* Map an /overview brand item (API shape) to the UI row shape.
|
||||
*
|
||||
* Note: `description` is not returned by /overview — it is fetched
|
||||
* lazily and cached per brand via `get_brand()`.
|
||||
*
|
||||
* @param array $brand Raw brand item.
|
||||
*
|
||||
* @return array
|
||||
@@ -289,7 +375,10 @@ class Brands_Controller extends Base_Controller {
|
||||
'name' => $brand['name'] ?? '',
|
||||
'url' => $brand['url'] ?? '',
|
||||
'locale' => $brand['country_code'] ?? null,
|
||||
'language' => $brand['language'] ?? null,
|
||||
'status' => ! empty( $brand['active'] ) ? 'active' : 'inactive',
|
||||
'interval' => $brand['analysis_frequency'] ?? null,
|
||||
'platforms' => Platforms::sanitize( $brand['platforms'] ?? [] ),
|
||||
'score' => $brand['ai_visibility_score'] ?? null,
|
||||
'rank' => $brand['rank'] ?? null,
|
||||
'avg_sentiment' => $brand['avg_sentiment'] ?? null,
|
||||
@@ -303,9 +392,7 @@ class Brands_Controller extends Base_Controller {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the dashboard response envelope, applying the optional search
|
||||
* filter (name/URL) against the stored rows. The filter never affects
|
||||
* what is cached — only what is returned.
|
||||
* Build the dashboard response envelope, applying the optional search filter.
|
||||
*
|
||||
* @param array $data Cached dashboard payload.
|
||||
* @param bool $is_stale Whether the payload is past its TTL.
|
||||
@@ -352,8 +439,7 @@ class Brands_Controller extends Base_Controller {
|
||||
return $this->success( [ 'brand' => $cached ] );
|
||||
}
|
||||
|
||||
// /overview omits `description`, so the single-brand endpoint is the
|
||||
// canonical source for full identity. Fetched once, then cached.
|
||||
// /overview omits `description`; fetch full identity once and cache it.
|
||||
$result = $this->remote_request( 'GET', '/api/v1/brands/' . $uuid );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
@@ -375,17 +461,48 @@ class Brands_Controller extends Base_Controller {
|
||||
* @return \WP_REST_Response|\WP_Error
|
||||
*/
|
||||
public function create_brand( $request ) {
|
||||
$locale = $request->get_param( 'locale' );
|
||||
$result = $this->remote_request(
|
||||
'POST',
|
||||
'/api/v1/brands',
|
||||
[
|
||||
'name' => sanitize_text_field( (string) $request->get_param( 'name' ) ),
|
||||
'url' => esc_url_raw( (string) $request->get_param( 'url' ) ),
|
||||
'description' => sanitize_textarea_field( (string) $request->get_param( 'description' ) ),
|
||||
'country_code' => $locale ? strtoupper( (string) $locale ) : '',
|
||||
]
|
||||
);
|
||||
$locale = $request->get_param( 'locale' );
|
||||
$language = $request->get_param( 'language' );
|
||||
$interval = $request->get_param( 'interval' );
|
||||
$platforms = $request->get_param( 'platforms' );
|
||||
|
||||
// Re-validate: the create-brand ability bypasses the REST arg constraints.
|
||||
$valid = Platforms::validate( $platforms );
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $valid;
|
||||
}
|
||||
|
||||
$platforms = Platforms::sanitize( $platforms );
|
||||
|
||||
if ( ! $language ) {
|
||||
return $this->error(
|
||||
'aiv_bad_request',
|
||||
__( 'Please select a language for this brand.', 'seo-by-rank-math' ),
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
$body = [
|
||||
'name' => sanitize_text_field( (string) $request->get_param( 'name' ) ),
|
||||
'url' => esc_url_raw( (string) $request->get_param( 'url' ) ),
|
||||
'description' => sanitize_textarea_field( (string) $request->get_param( 'description' ) ),
|
||||
'language' => (string) $language,
|
||||
'platforms' => $platforms,
|
||||
];
|
||||
|
||||
// Omit rather than send '' — the backend rejects an explicit empty string.
|
||||
if ( $locale ) {
|
||||
$body['country_code'] = strtoupper( (string) $locale );
|
||||
}
|
||||
if ( $interval ) {
|
||||
$allowed = $this->check_interval_allowed( $interval );
|
||||
if ( is_wp_error( $allowed ) ) {
|
||||
return $allowed;
|
||||
}
|
||||
$body['analysis_frequency'] = (string) $interval;
|
||||
}
|
||||
|
||||
$result = $this->remote_request( 'POST', '/api/v1/brands', $body );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
@@ -394,9 +511,7 @@ class Brands_Controller extends Base_Controller {
|
||||
$brand = $this->map_brand( $result );
|
||||
$uuid = $brand['id'];
|
||||
|
||||
// Prime caches from the create response. Creation atomically seeds a
|
||||
// pending analysis, so the row starts as `pending` (no last_analyzed) —
|
||||
// this is what makes it eligible for the first-analysis poller.
|
||||
// Row starts as `pending` — creation atomically seeds the first analysis.
|
||||
Cache::append_brand_row(
|
||||
array_merge(
|
||||
$brand,
|
||||
@@ -421,8 +536,9 @@ class Brands_Controller extends Base_Controller {
|
||||
'AI Visibility Brand Created',
|
||||
[
|
||||
'locale' => $brand['locale'] ?? null,
|
||||
'interval' => 'weekly',
|
||||
'platforms' => [ 'chatgpt' ],
|
||||
'language' => $brand['language'] ?? null,
|
||||
'interval' => $brand['interval'] ?? null,
|
||||
'platforms' => $platforms,
|
||||
]
|
||||
);
|
||||
|
||||
@@ -460,6 +576,31 @@ class Brands_Controller extends Base_Controller {
|
||||
$body['country_code'] = strtoupper( sanitize_text_field( $locale ) );
|
||||
}
|
||||
|
||||
// Omit blank values — the backend rejects an explicit empty string.
|
||||
$language = $request->get_param( 'language' );
|
||||
if ( $language ) {
|
||||
$body['language'] = sanitize_text_field( $language );
|
||||
}
|
||||
|
||||
$interval = $request->get_param( 'interval' );
|
||||
if ( null !== $interval ) {
|
||||
$allowed = $this->check_interval_allowed( $interval );
|
||||
if ( is_wp_error( $allowed ) ) {
|
||||
return $allowed;
|
||||
}
|
||||
$body['analysis_frequency'] = sanitize_text_field( $interval );
|
||||
}
|
||||
|
||||
$platforms = $request->get_param( 'platforms' );
|
||||
if ( null !== $platforms ) {
|
||||
$valid = Platforms::validate( $platforms );
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $valid;
|
||||
}
|
||||
|
||||
$body['platforms'] = Platforms::sanitize( $platforms );
|
||||
}
|
||||
|
||||
if ( empty( $body ) ) {
|
||||
return $this->error( 'aiv_bad_request', __( 'No fields to update.', 'seo-by-rank-math' ), 400 );
|
||||
}
|
||||
@@ -472,7 +613,6 @@ class Brands_Controller extends Base_Controller {
|
||||
|
||||
$brand = $this->map_brand( isset( $result['data'] ) ? $result['data'] : $result );
|
||||
|
||||
// Write-through: patch the dashboard row, replace the identity transient.
|
||||
Cache::patch_brand_row(
|
||||
$uuid,
|
||||
[
|
||||
@@ -480,7 +620,10 @@ class Brands_Controller extends Base_Controller {
|
||||
'url' => $brand['url'],
|
||||
'description' => $brand['description'],
|
||||
'locale' => $brand['locale'],
|
||||
'language' => $brand['language'],
|
||||
'status' => $brand['status'],
|
||||
'interval' => $brand['interval'],
|
||||
'platforms' => $brand['platforms'],
|
||||
]
|
||||
);
|
||||
Cache::set_brand( $uuid, $brand );
|
||||
@@ -492,6 +635,8 @@ class Brands_Controller extends Base_Controller {
|
||||
'fields_changed' => array_keys( $body ),
|
||||
'status_changed' => $status_changed,
|
||||
'new_status' => $status_changed ? $brand['status'] : null,
|
||||
'platforms' => $brand['platforms'],
|
||||
'language' => $brand['language'] ?? null,
|
||||
]
|
||||
);
|
||||
|
||||
@@ -512,9 +657,12 @@ class Brands_Controller extends Base_Controller {
|
||||
'url' => $brand['url'] ?? '',
|
||||
'description' => $brand['description'] ?? '',
|
||||
'locale' => $brand['country_code'] ?? null,
|
||||
'language' => $brand['language'] ?? null,
|
||||
'status' => $brand['status'] ?? 'active',
|
||||
'interval' => $brand['analysis_frequency'] ?? null,
|
||||
'last_analyzed' => $brand['last_analyzed_at'] ?? null,
|
||||
'created_at' => $brand['created_at'] ?? null,
|
||||
'platforms' => Platforms::sanitize( $brand['platforms'] ?? [] ),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -568,15 +716,22 @@ class Brands_Controller extends Base_Controller {
|
||||
);
|
||||
|
||||
// Keep the dashboard row's summary in sync (poller success path).
|
||||
$finished_ats = array_filter( array_column( $insights['analyses'], 'finished_at' ) );
|
||||
|
||||
// Resolve status here rather than relying on /overview, which can lag.
|
||||
$analysis_statuses = array_column( $insights['analyses'], 'status' );
|
||||
$analysis_status = in_array( 'error', $analysis_statuses, true ) ? 'error' : 'success';
|
||||
|
||||
Cache::patch_brand_row(
|
||||
$uuid,
|
||||
[
|
||||
'score' => $insights['score'],
|
||||
'rank' => $insights['rank'],
|
||||
'avg_sentiment' => $insights['avg_sentiment'],
|
||||
'mentions' => $insights['mentions'],
|
||||
'citations' => $insights['citations'],
|
||||
'last_analyzed' => $insights['analysis']['finished_at'],
|
||||
'score' => $insights['score'],
|
||||
'rank' => $insights['rank'],
|
||||
'avg_sentiment' => $insights['avg_sentiment'],
|
||||
'mentions' => $insights['mentions'],
|
||||
'citations' => $insights['citations'],
|
||||
'last_analyzed' => $finished_ats ? max( $finished_ats ) : null,
|
||||
'analysis_status' => $analysis_status,
|
||||
]
|
||||
);
|
||||
|
||||
@@ -591,7 +746,7 @@ class Brands_Controller extends Base_Controller {
|
||||
* @return array
|
||||
*/
|
||||
private function map_insights( $result ) {
|
||||
$analysis = isset( $result['analysis'] ) ? (array) $result['analysis'] : [];
|
||||
$analyses = isset( $result['analyses'] ) ? (array) $result['analyses'] : [];
|
||||
|
||||
return [
|
||||
'score' => $result['ai_visibility_score'] ?? null,
|
||||
@@ -599,14 +754,19 @@ class Brands_Controller extends Base_Controller {
|
||||
'avg_sentiment' => $result['avg_sentiment'] ?? null,
|
||||
'mentions' => $result['mentions'] ?? null,
|
||||
'citations' => $result['citations'] ?? null,
|
||||
'analysis' => [
|
||||
'id' => $analysis['uuid'] ?? null,
|
||||
// Map the API status vocabulary to the UI one (`success` → `done`).
|
||||
'status' => isset( $analysis['status'] ) && 'success' === $analysis['status'] ? 'done' : ( $analysis['status'] ?? null ),
|
||||
'started_at' => $analysis['started_at'] ?? null,
|
||||
'finished_at' => $analysis['finished_at'] ?? null,
|
||||
'duration_seconds' => $analysis['duration_seconds'] ?? null,
|
||||
],
|
||||
'analyses' => array_map(
|
||||
function ( $analysis ) {
|
||||
return [
|
||||
'id' => $analysis['uuid'] ?? null,
|
||||
'platform' => $analysis['platform'] ?? null,
|
||||
'status' => isset( $analysis['status'] ) && 'success' === $analysis['status'] ? 'done' : ( $analysis['status'] ?? null ),
|
||||
'started_at' => $analysis['started_at'] ?? null,
|
||||
'finished_at' => $analysis['finished_at'] ?? null,
|
||||
'duration_seconds' => $analysis['duration_seconds'] ?? null,
|
||||
];
|
||||
},
|
||||
$analyses
|
||||
),
|
||||
'competitors' => array_map(
|
||||
function ( $competitor ) {
|
||||
return [
|
||||
@@ -623,6 +783,7 @@ class Brands_Controller extends Base_Controller {
|
||||
return [
|
||||
'query_id' => $query_result['query_uuid'] ?? null,
|
||||
'query_text' => $query_result['query_text'] ?? '',
|
||||
'platform' => $query_result['platform'] ?? null,
|
||||
'found' => ! empty( $query_result['found'] ),
|
||||
'rank' => $query_result['rank_among_competitors'] ?? null,
|
||||
'sentiment' => $query_result['sentiment_score'] ?? null,
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+10
-10
@@ -7,7 +7,7 @@
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { useMemo, useState, useEffect } from '@wordpress/element'
|
||||
import { useMemo, useState, useEffect, useRef } from '@wordpress/element'
|
||||
import { __ } from '@wordpress/i18n'
|
||||
import { SelectControl, SearchControl, Button } from '@wordpress/components'
|
||||
|
||||
@@ -43,28 +43,31 @@ const AnalysesFilterBar = ( {
|
||||
} ) => {
|
||||
const ns = 'rank-math-ai-visibility-analyses-filter-bar'
|
||||
|
||||
// Prepend "All Brands" option to the brand list.
|
||||
const brandSelectOptions = useMemo( () => [
|
||||
{ label: __( 'All Brands', 'seo-by-rank-math' ), value: '' },
|
||||
...brandOptions,
|
||||
], [ brandOptions ] )
|
||||
|
||||
// The hook stores brandIds as an array. For the single-select UI we store
|
||||
// the first item (or '') and convert back on change.
|
||||
// brandIds is an array; the single-select UI only needs the first item.
|
||||
const activeBrandId = ( filters.brandIds && filters.brandIds[ 0 ] )
|
||||
? String( filters.brandIds[ 0 ] )
|
||||
: ''
|
||||
|
||||
// Local search state — debounced 300 ms before propagating to the hook.
|
||||
// This prevents a new API request on every keystroke.
|
||||
const [ localSearch, setLocalSearch ] = useState( filters.search || '' )
|
||||
const isFirstSearchRender = useRef( true )
|
||||
|
||||
// Sync local state if the parent resets filters externally (e.g. "clear all").
|
||||
// Sync when the parent resets filters externally (e.g. "clear all").
|
||||
useEffect( () => {
|
||||
setLocalSearch( filters.search || '' )
|
||||
}, [ filters.search ] )
|
||||
|
||||
// Skip on mount — avoids a no-op filter change resetting pagination.
|
||||
useEffect( () => {
|
||||
if ( isFirstSearchRender.current ) {
|
||||
isFirstSearchRender.current = false
|
||||
return
|
||||
}
|
||||
|
||||
const timer = setTimeout( () => {
|
||||
onFilterChange( { search: localSearch } )
|
||||
}, 300 )
|
||||
@@ -82,7 +85,6 @@ const AnalysesFilterBar = ( {
|
||||
return (
|
||||
<div className={ ns }>
|
||||
|
||||
{ /* Brand — standard SelectControl, matches Status style */ }
|
||||
<SelectControl
|
||||
className={ `${ ns }__brand` }
|
||||
value={ activeBrandId }
|
||||
@@ -102,7 +104,6 @@ const AnalysesFilterBar = ( {
|
||||
__nextHasNoMarginBottom={ true }
|
||||
/>
|
||||
|
||||
{ /* Search — value bound to local state; propagation is debounced 300 ms */ }
|
||||
<SearchControl
|
||||
className={ `${ ns }__search` }
|
||||
placeholder={ __( 'Search', 'seo-by-rank-math' ) }
|
||||
@@ -123,7 +124,6 @@ const AnalysesFilterBar = ( {
|
||||
</Button>
|
||||
) }
|
||||
|
||||
{ /* Date range: [📅 From] - [📅 To] */ }
|
||||
<div className={ `${ ns }__dates` }>
|
||||
<div className={ `${ ns }__date-wrap` }>
|
||||
<DateInput
|
||||
|
||||
+27
-15
@@ -26,20 +26,28 @@ import './AnalysisRunDetail.scss'
|
||||
/**
|
||||
* Map an insights query result to the shape TranscriptModal expects.
|
||||
*
|
||||
* The id is qualified by platform — the backend reuses the same query_id
|
||||
* across platforms, so an unqualified id would collide.
|
||||
*
|
||||
* @param {Object} result Query result from the insights payload.
|
||||
* @param {number} index Fallback index.
|
||||
* @param {Object} analysis Parent analysis meta.
|
||||
* @param {Object} analysis Analysis run (matched by platform) this result belongs to.
|
||||
* @return {Object} Normalised entry.
|
||||
*/
|
||||
const normalise = ( result, index, analysis ) => ( {
|
||||
...result,
|
||||
id: result.query_id ?? index,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
model: null,
|
||||
} )
|
||||
const normalise = ( result, index, analysis ) => {
|
||||
const baseId = result.query_id ?? index
|
||||
const platform = result.platform ?? 'default'
|
||||
|
||||
return {
|
||||
...result,
|
||||
id: `${ baseId }-${ platform }`,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
model: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AnalysisRunDetail component.
|
||||
@@ -60,10 +68,14 @@ const AnalysisRunDetail = ( { row, onBack } ) => {
|
||||
const insights = insightsData?.insights ?? null
|
||||
const [ modalEntry, setModalEntry ] = useState( null )
|
||||
|
||||
const transcripts = ( insights?.query_results ?? [] ).map( ( result, i ) => normalise( result, i, insights?.analysis ) )
|
||||
const totalDuration = insights?.analysis?.duration_seconds ?? 0
|
||||
const analyses = insights?.analyses ?? []
|
||||
const findAnalysis = ( platform ) => analyses.find( ( analysis ) => analysis.platform === platform ) ?? analyses[ 0 ] ?? null
|
||||
|
||||
const transcripts = ( insights?.query_results ?? [] ).map( ( result, i ) => normalise( result, i, findAnalysis( result.platform ) ) )
|
||||
const totalDuration = analyses.reduce( ( sum, analysis ) => sum + ( analysis.duration_seconds ?? 0 ), 0 )
|
||||
const durationLabel = totalDuration ? `${ totalDuration }s` : '—'
|
||||
const startedAt = row?.started_at ?? insights?.analysis?.started_at
|
||||
const startedAts = analyses.map( ( analysis ) => analysis.started_at ).filter( Boolean ).sort()
|
||||
const startedAt = row?.started_at ?? startedAts[ 0 ]
|
||||
|
||||
const handleExportReport = () => navigateToReportsTab( row.id )
|
||||
|
||||
@@ -94,7 +106,7 @@ const AnalysisRunDetail = ( { row, onBack } ) => {
|
||||
value={ row?.brand_name || '—' }
|
||||
className="rank-math-ai-visibility-stat-card--target-brand"
|
||||
tooltip={ __( 'The brand this analysis run is for.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ analyses[ 0 ] ?? null }
|
||||
/>
|
||||
|
||||
<StatCard
|
||||
@@ -105,7 +117,7 @@ const AnalysisRunDetail = ( { row, onBack } ) => {
|
||||
sub={ formatShortDate( startedAt ) }
|
||||
className="rank-math-ai-visibility-stat-card--duration-timing"
|
||||
tooltip={ __( 'Total duration of all queries in this run, and the date it was started.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ analyses[ 0 ] ?? null }
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
+14
-25
@@ -20,6 +20,7 @@ import { addQueryArgs } from '@wordpress/url'
|
||||
* Internal dependencies
|
||||
*/
|
||||
import useDashboard from '../shared/hooks/useDashboard'
|
||||
import usePagination from '../shared/hooks/usePagination'
|
||||
import { getAnalysisState } from '../utils/analysisState'
|
||||
import { SectionHeader } from '../shared/components'
|
||||
import AnalysesFilterBar from './AnalysesFilterBar'
|
||||
@@ -36,20 +37,15 @@ const DEFAULT_FILTERS = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync filters + pagination into the URL without reloading.
|
||||
*
|
||||
* @param {Object} filters Active filter bag.
|
||||
* @param {Object} pagination Active pagination.
|
||||
* @param {Object} filters Active filter bag.
|
||||
*/
|
||||
const writeToUrl = ( filters, pagination ) => {
|
||||
const writeFiltersToUrl = ( filters ) => {
|
||||
const params = {
|
||||
aiv_brands: filters.brandIds.length ? filters.brandIds.join( ',' ) : undefined,
|
||||
aiv_status: filters.status || undefined,
|
||||
aiv_search: filters.search || undefined,
|
||||
aiv_from: filters.dateFrom || undefined,
|
||||
aiv_to: filters.dateTo || undefined,
|
||||
aiv_page: pagination.page > 1 ? pagination.page : undefined,
|
||||
aiv_per: pagination.perPage !== 10 ? pagination.perPage : undefined,
|
||||
}
|
||||
|
||||
const url = addQueryArgs( window.location.href, params )
|
||||
@@ -70,8 +66,7 @@ const toRunRow = ( brand ) => {
|
||||
brand_id: brand.id,
|
||||
brand_name: brand.name,
|
||||
started_at: brand.last_analyzed,
|
||||
// Display/filter bucket: running | error | done | none. Same icon
|
||||
// derivation as the Dashboard column, so the two tabs never disagree.
|
||||
// Matches the Dashboard column's derivation, so both tabs agree.
|
||||
status: state ?? ( brand.last_analyzed ? 'done' : 'none' ),
|
||||
}
|
||||
}
|
||||
@@ -85,7 +80,6 @@ const Analyses = () => {
|
||||
const { brands, loading, error } = useDashboard()
|
||||
|
||||
const [ filters, setFilters ] = useState( DEFAULT_FILTERS )
|
||||
const [ pagination, setPagination ] = useState( { page: 1, perPage: 10 } )
|
||||
const [ selectedRow, setSelectedRow ] = useState( null )
|
||||
|
||||
const brandOptions = useMemo(
|
||||
@@ -93,7 +87,6 @@ const Analyses = () => {
|
||||
[ brands ]
|
||||
)
|
||||
|
||||
// Derive + filter rows client-side.
|
||||
const filteredItems = useMemo( () => {
|
||||
return brands.map( toRunRow ).filter( ( item ) => {
|
||||
if ( filters.search && ! item.brand_name.toLowerCase().includes( filters.search.toLowerCase() ) ) {
|
||||
@@ -118,26 +111,22 @@ const Analyses = () => {
|
||||
} )
|
||||
}, [ brands, filters ] )
|
||||
|
||||
const total = filteredItems.length
|
||||
const pages = Math.max( 1, Math.ceil( total / pagination.perPage ) )
|
||||
const pageItems = useMemo( () => {
|
||||
const offset = ( pagination.page - 1 ) * pagination.perPage
|
||||
return filteredItems.slice( offset, offset + pagination.perPage )
|
||||
}, [ filteredItems, pagination ] )
|
||||
const { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage } =
|
||||
usePagination( filteredItems, { perPage: 10, syncUrl: true } )
|
||||
|
||||
const handleFilterChange = useCallback( ( patch ) => {
|
||||
setFilters( ( prev ) => ( { ...prev, ...patch } ) )
|
||||
setPagination( ( prev ) => ( { ...prev, page: 1 } ) )
|
||||
}, [] )
|
||||
resetPage()
|
||||
}, [ resetPage ] )
|
||||
|
||||
const handleClearFilters = useCallback( () => {
|
||||
setFilters( DEFAULT_FILTERS )
|
||||
setPagination( ( prev ) => ( { ...prev, page: 1 } ) )
|
||||
}, [] )
|
||||
resetPage()
|
||||
}, [ resetPage ] )
|
||||
|
||||
useEffect( () => {
|
||||
writeToUrl( filters, pagination )
|
||||
}, [ filters, pagination ] )
|
||||
writeFiltersToUrl( filters )
|
||||
}, [ filters ] )
|
||||
|
||||
if ( selectedRow ) {
|
||||
return (
|
||||
@@ -177,8 +166,8 @@ const Analyses = () => {
|
||||
loading={ loading }
|
||||
pagination={ { ...pagination, total, pages } }
|
||||
onViewDetail={ ( row ) => setSelectedRow( row ) }
|
||||
onPageChange={ ( page ) => setPagination( ( prev ) => ( { ...prev, page: Math.max( 1, page ) } ) ) }
|
||||
onPerPageChange={ ( perPage ) => setPagination( { page: 1, perPage: Math.max( 1, perPage ) } ) }
|
||||
onPageChange={ onPageChange }
|
||||
onPerPageChange={ onPerPageChange }
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
+2
-2
@@ -76,7 +76,7 @@ const App = ( { config = {} } ) => {
|
||||
setActiveTab( tabName )
|
||||
}
|
||||
|
||||
const { isSiteConnected, isPro, plan, locales = [] } = rankMath.aiVisibility
|
||||
const { isSiteConnected, isPro, plan, locales = [], languages = [], defaultLanguage = '', intervals = [], platforms = {}, maxPlatforms = 1 } = rankMath.aiVisibility
|
||||
|
||||
// Access gate — Free Content AI plan: PRO users get the trial flow,
|
||||
// free plugin users get the upgrade modal.
|
||||
@@ -100,7 +100,7 @@ const App = ( { config = {} } ) => {
|
||||
<div className={ 'rank-math-ai-visibility__tab rank-math-ai-visibility__tab--' + tab.name }>
|
||||
{ ! isSiteConnected && <Connect config={ config } /> }
|
||||
{ isSiteConnected && (
|
||||
isPlanGated ? <GatedPreview /> : createElement( tab.view, { locales, onBrandCreated: showSnackbar } )
|
||||
isPlanGated ? <GatedPreview /> : createElement( tab.view, { locales, languages, defaultLanguage, intervals, platforms, maxPlatforms, onBrandCreated: showSnackbar } )
|
||||
) }
|
||||
</div>
|
||||
) }
|
||||
|
||||
+5
@@ -72,6 +72,11 @@ const BrandHeader = ( {
|
||||
{ brand.url }
|
||||
</a>
|
||||
{ brand.locale && <CountryFlag locale={ brand.locale } /> }
|
||||
{ brand.language && (
|
||||
<span className={ `${ ns }__language` }>
|
||||
{ brand.language }
|
||||
</span>
|
||||
) }
|
||||
<a
|
||||
className={ `${ ns }__external` }
|
||||
href={ getBrandUrl( brand.url ) }
|
||||
|
||||
+10
@@ -81,6 +81,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
&__language {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 20px;
|
||||
font-size: 11px;
|
||||
color: $color-text-muted;
|
||||
border: 1px solid $color-border;
|
||||
}
|
||||
|
||||
&__external {
|
||||
color: #757575;
|
||||
display: inline-flex;
|
||||
|
||||
+3
-3
@@ -50,7 +50,7 @@ const BrandOverview = ( { brand, insights = null, loading = false } ) => {
|
||||
: placeholder
|
||||
}
|
||||
tooltip={ __( 'AI Visibility Score for this brand across AI platforms.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ insights?.analyses?.[ 0 ] }
|
||||
/>
|
||||
|
||||
<StatCard
|
||||
@@ -71,7 +71,7 @@ const BrandOverview = ( { brand, insights = null, loading = false } ) => {
|
||||
: placeholder
|
||||
}
|
||||
tooltip={ __( 'Average sentiment score across all AI mentions of this brand.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ insights?.analyses?.[ 0 ] }
|
||||
/>
|
||||
|
||||
<StatCard
|
||||
@@ -98,7 +98,7 @@ const BrandOverview = ( { brand, insights = null, loading = false } ) => {
|
||||
label={ __( 'Top Competitor', 'seo-by-rank-math' ) }
|
||||
value={ topCompetitor || placeholder }
|
||||
tooltip={ __( 'The competitor brand with the highest share of voice in AI mentions.', 'seo-by-rank-math' ) }
|
||||
analysis={ insights?.analysis }
|
||||
analysis={ insights?.analyses?.[ 0 ] }
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
+25
-12
@@ -20,21 +20,29 @@ import './RunDetail.scss'
|
||||
/**
|
||||
* Map an insights query result to the shape TranscriptViewer expects.
|
||||
*
|
||||
* The id is qualified by platform — the backend reuses the same query_id
|
||||
* across platforms, so an unqualified id would collide.
|
||||
*
|
||||
* @param {Object} result Query result from the insights payload.
|
||||
* @param {number} index Fallback index.
|
||||
* @param {Object} analysis Parent analysis meta.
|
||||
* @param {Object} analysis Analysis run (matched by platform) this result belongs to.
|
||||
* @return {Object} Normalised entry.
|
||||
*/
|
||||
const toEntry = ( result, index, analysis ) => ( {
|
||||
...result,
|
||||
id: result.query_id ?? index,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
status: result.found ? 'success' : 'partial',
|
||||
model: null,
|
||||
} )
|
||||
const toEntry = ( result, index, analysis ) => {
|
||||
const baseId = result.query_id ?? index
|
||||
const platform = result.platform ?? 'default'
|
||||
|
||||
return {
|
||||
...result,
|
||||
id: `${ baseId }-${ platform }`,
|
||||
query: result.query_text ?? '',
|
||||
response: result.response ?? '',
|
||||
created_at: analysis?.finished_at ?? null,
|
||||
duration_seconds: analysis?.duration_seconds ?? null,
|
||||
status: result.found ? 'success' : 'partial',
|
||||
model: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} props
|
||||
@@ -44,7 +52,12 @@ const toEntry = ( result, index, analysis ) => ( {
|
||||
*/
|
||||
const RunDetail = ( { insights = null, loading = false } ) => {
|
||||
const entries = useMemo(
|
||||
() => ( insights?.query_results ?? [] ).map( ( result, i ) => toEntry( result, i, insights?.analysis ) ),
|
||||
() => {
|
||||
const analyses = insights?.analyses ?? []
|
||||
const findAnalysis = ( platform ) => analyses.find( ( analysis ) => analysis.platform === platform ) ?? analyses[ 0 ] ?? null
|
||||
|
||||
return ( insights?.query_results ?? [] ).map( ( result, i ) => toEntry( result, i, findAnalysis( result.platform ) ) )
|
||||
},
|
||||
[ insights ]
|
||||
)
|
||||
|
||||
|
||||
+11
-1
@@ -55,9 +55,14 @@ const SUB_TABS = [
|
||||
* @param {number} props.brandId
|
||||
* @param {Function} [props.onBack]
|
||||
* @param {Array} [props.locales]
|
||||
* @param {Array} [props.languages]
|
||||
* @param {string} [props.defaultLanguage] Default language for new brands (site language).
|
||||
* @param {Array} [props.intervals]
|
||||
* @param {Object} [props.platforms] AI platform registry from PHP.
|
||||
* @param {number} [props.maxPlatforms] Platforms selectable on the current plan.
|
||||
* @return {JSX.Element} Rendered component.
|
||||
*/
|
||||
const BrandDetail = ( { brandId, onBack, locales = [] } ) => {
|
||||
const BrandDetail = ( { brandId, onBack, locales = [], languages = [], defaultLanguage = '', intervals = [], platforms = {}, maxPlatforms = 1 } ) => {
|
||||
const handleBack = onBack || navigateBackToDashboard
|
||||
const { data: brandData, loading, error, setData: setBrandData } = useFetch(
|
||||
() => getBrand( brandId ),
|
||||
@@ -165,6 +170,11 @@ const BrandDetail = ( { brandId, onBack, locales = [] } ) => {
|
||||
isSaving={ isSaving }
|
||||
apiError={ saveError }
|
||||
locales={ locales }
|
||||
languages={ languages }
|
||||
defaultLanguage={ defaultLanguage }
|
||||
intervals={ intervals }
|
||||
platforms={ platforms }
|
||||
maxPlatforms={ maxPlatforms }
|
||||
/>
|
||||
) }
|
||||
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ const GatedPreview = () => {
|
||||
<StatCard
|
||||
className="rank-math-ai-visibility-stat-card--analyses"
|
||||
icon={ trendingUp }
|
||||
label={ __( 'Analyses in last 24h', 'seo-by-rank-math' ) }
|
||||
label={ __( 'Analyses in the last 7 days', 'seo-by-rank-math' ) }
|
||||
value={ 0 }
|
||||
/>
|
||||
<StatCard
|
||||
|
||||
+36
-15
@@ -21,6 +21,7 @@ import { trendingUp, store } from '@wordpress/icons'
|
||||
* Internal dependencies
|
||||
*/
|
||||
import useDashboard from '../shared/hooks/useDashboard'
|
||||
import usePagination from '../shared/hooks/usePagination'
|
||||
import { getBrand } from '../shared/services/api/aiVisibilityApi'
|
||||
import { StatCard, EmptyState } from '../shared/components'
|
||||
import { ConfirmModal, AddBrandModal, UpgradePlanModal } from '../shared/Modals'
|
||||
@@ -67,11 +68,11 @@ const getConfirmMessage = ( confirmBrand, confirmAction ) => {
|
||||
/**
|
||||
* Resolve the display value for a summary StatCard.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {boolean} options.loading Whether the dashboard is still loading.
|
||||
* @param {boolean} options.hasBrands Whether any brands are tracked.
|
||||
* @param {*} options.raw Raw summary value (may be null/undefined).
|
||||
* @param {Function} [options.format] Optional formatter for a present value.
|
||||
* @param {Object} options
|
||||
* @param {boolean} options.loading Whether the dashboard is still loading.
|
||||
* @param {boolean} options.hasBrands Whether any brands are tracked.
|
||||
* @param {*} options.raw Raw summary value (may be null/undefined).
|
||||
* @param {Function} [options.format] Optional formatter for a present value.
|
||||
* @return {string|number|null} Placeholder, null (empty), 0 (missing) or formatted value.
|
||||
*/
|
||||
const getStatValue = ( { loading, hasBrands, raw, format } ) => {
|
||||
@@ -89,11 +90,16 @@ const getStatValue = ( { loading, hasBrands, raw, format } ) => {
|
||||
|
||||
/**
|
||||
* @param {Object} props
|
||||
* @param {Array} [props.locales] Locale options for the brand modals.
|
||||
* @param {Function} [props.onBrandCreated] Callback when a new brand is successfully created.
|
||||
* @param {Array} [props.locales] Locale options for the brand modals.
|
||||
* @param {Array} [props.languages] Output language options for the brand modals.
|
||||
* @param {string} [props.defaultLanguage] Default language for new brands (site language).
|
||||
* @param {Object} [props.platforms] AI platform registry from PHP.
|
||||
* @param {number} [props.maxPlatforms] Platforms selectable on the current plan.
|
||||
* @param {Function} [props.onBrandCreated] Callback when a new brand is successfully created.
|
||||
* @param {Array} [props.intervals] Interval options for the brand modals.
|
||||
* @return {JSX.Element} Rendered component.
|
||||
*/
|
||||
const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
const Dashboard = ( { locales = [], languages = [], defaultLanguage = '', platforms = {}, maxPlatforms = 1, onBrandCreated = () => {}, intervals = [] } ) => {
|
||||
const [ activeBrandId, setActiveBrandId ] = useState( getActiveBrandId )
|
||||
|
||||
useEffect( () => {
|
||||
@@ -114,13 +120,11 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
handleEnableBrand,
|
||||
} = useDashboard()
|
||||
|
||||
// Modal state
|
||||
const [ isAddModalOpen, setAddModalOpen ] = useState( false )
|
||||
const [ editBrand, setEditBrand ] = useState( null )
|
||||
const [ isSaving, setIsSaving ] = useState( false )
|
||||
const [ saveError, setSaveError ] = useState( null )
|
||||
|
||||
// ConfirmModal state
|
||||
const [ confirmBrand, setConfirmBrand ] = useState( null )
|
||||
const [ confirmAction, setConfirmAction ] = useState( 'delete' )
|
||||
const [ isProcessing, setIsProcessing ] = useState( false )
|
||||
@@ -128,10 +132,13 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
|
||||
const [ isUpgradeModalOpen, setUpgradeModalOpen ] = useState( false )
|
||||
|
||||
// Search: debounced 300 ms, proxy filters cached rows server-side.
|
||||
// Search is debounced 300ms.
|
||||
const [ searchQuery, setSearchQuery ] = useState( '' )
|
||||
const isFirstSearchRender = useRef( true )
|
||||
|
||||
const { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage } =
|
||||
usePagination( brands, { perPage: 10, syncUrl: true } )
|
||||
|
||||
useEffect( () => {
|
||||
if ( isFirstSearchRender.current ) {
|
||||
isFirstSearchRender.current = false
|
||||
@@ -140,9 +147,10 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
|
||||
const timer = setTimeout( () => {
|
||||
handleSearch( searchQuery.trim() )
|
||||
resetPage()
|
||||
}, 300 )
|
||||
return () => clearTimeout( timer )
|
||||
}, [ searchQuery, handleSearch ] )
|
||||
}, [ searchQuery, handleSearch, resetPage ] )
|
||||
|
||||
const hasActiveSearch = !! searchQuery.trim()
|
||||
const isEmpty = ! loading && brands.length === 0 && ! hasActiveSearch
|
||||
@@ -234,6 +242,11 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
brandId={ activeBrandId }
|
||||
onBack={ handleBackToDashboard }
|
||||
locales={ locales }
|
||||
languages={ languages }
|
||||
defaultLanguage={ defaultLanguage }
|
||||
intervals={ intervals }
|
||||
platforms={ platforms }
|
||||
maxPlatforms={ maxPlatforms }
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -260,8 +273,8 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
<StatCard
|
||||
className="rank-math-ai-visibility-stat-card--analyses"
|
||||
icon={ trendingUp }
|
||||
label={ __( 'Analyses in last 24h', 'seo-by-rank-math' ) }
|
||||
value={ getStatValue( { loading, hasBrands: brands.length > 0, raw: summary?.analyses_last_24h } ) }
|
||||
label={ __( 'Analyses in the last 7 days', 'seo-by-rank-math' ) }
|
||||
value={ getStatValue( { loading, hasBrands: brands.length > 0, raw: summary?.analyses_last_7d } ) }
|
||||
tooltip={ __( 'Total analysis runs completed in the past 24 hours.', 'seo-by-rank-math' ) }
|
||||
/>
|
||||
<StatCard
|
||||
@@ -297,8 +310,9 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
/>
|
||||
|
||||
<BrandsTable
|
||||
brands={ brands }
|
||||
brands={ pageItems }
|
||||
loading={ loading }
|
||||
pagination={ { ...pagination, total, pages } }
|
||||
onView={ handleViewBrand }
|
||||
onEdit={ async ( brand ) => {
|
||||
setEditBrand( brand )
|
||||
@@ -313,6 +327,8 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
}
|
||||
} }
|
||||
onDisable={ ( brand ) => openDisableConfirm( brand ) }
|
||||
onPageChange={ onPageChange }
|
||||
onPerPageChange={ onPerPageChange }
|
||||
/>
|
||||
</div>
|
||||
) }
|
||||
@@ -325,6 +341,11 @@ const Dashboard = ( { locales = [], onBrandCreated = () => {} } ) => {
|
||||
isSaving={ isSaving }
|
||||
apiError={ saveError }
|
||||
locales={ locales }
|
||||
languages={ languages }
|
||||
defaultLanguage={ defaultLanguage }
|
||||
intervals={ intervals }
|
||||
platforms={ platforms }
|
||||
maxPlatforms={ maxPlatforms }
|
||||
/>
|
||||
) }
|
||||
|
||||
|
||||
+4
@@ -136,7 +136,11 @@ const Reports = () => {
|
||||
rows[ 0 ].competitors = ( data?.insights?.competitors ?? [] ).map( ( c ) => c.name )
|
||||
rows[ 0 ].queries = ( data?.insights?.query_results ?? [] ).map( ( q ) => ( {
|
||||
query: q.query_text ?? '',
|
||||
platform: q.platform ?? null,
|
||||
response: q.response ?? '',
|
||||
found: q.found ?? null,
|
||||
sentiment_score: q.sentiment ?? null,
|
||||
citations_count: q.citations ?? null,
|
||||
} ) )
|
||||
} catch {
|
||||
// Competitors and queries are nice-to-have in the report — ignore.
|
||||
|
||||
+120
-77
@@ -7,7 +7,7 @@
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n'
|
||||
import { __, _n, sprintf } from '@wordpress/i18n'
|
||||
import { useState, useEffect, useMemo, useRef } from '@wordpress/element'
|
||||
import { Modal, TextControl, TextareaControl, SelectControl, CheckboxControl, Icon } from '@wordpress/components'
|
||||
import { close } from '@wordpress/icons'
|
||||
@@ -19,54 +19,31 @@ import { SelectWithSearch } from '@rank-math/components'
|
||||
import Button from '../components/Button'
|
||||
import LoadingButton from '../components/LoadingButton'
|
||||
import getLink from '@helpers/getLink'
|
||||
import { toPlatformList, getDefaultPlatforms, getEnabledPlatformIds } from '../services/platforms'
|
||||
import './AddBrandModal.scss'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const EMPTY_FORM = {
|
||||
/**
|
||||
* Blank form state.
|
||||
*
|
||||
* @param {Array} platformList Available platforms.
|
||||
* @param {string} [defaultLanguage=''] Default language for a new brand (site language).
|
||||
* @return {Object} Empty form values.
|
||||
*/
|
||||
const emptyForm = ( platformList, defaultLanguage = '' ) => ( {
|
||||
name: '',
|
||||
url: '',
|
||||
description: '',
|
||||
locale: '',
|
||||
interval: 'weekly',
|
||||
platforms: [ 'chatgpt' ],
|
||||
}
|
||||
language: defaultLanguage,
|
||||
interval: 'monthly',
|
||||
platforms: getDefaultPlatforms( platformList ),
|
||||
} )
|
||||
|
||||
/**
|
||||
* Order in which fields are validated / scrolled to.
|
||||
* Used to focus the first errored field on a failed save.
|
||||
*/
|
||||
const FIELD_ORDER = [ 'name', 'url', 'description' ]
|
||||
|
||||
/**
|
||||
* Analysis interval options.
|
||||
*/
|
||||
const INTERVAL_OPTIONS = [
|
||||
{ label: __( 'Weekly', 'seo-by-rank-math' ), value: 'weekly', disabled: false },
|
||||
{ label: __( 'Monthly (Coming Soon)', 'seo-by-rank-math' ), value: 'monthly', disabled: true },
|
||||
{ label: __( 'Daily (Coming Soon)', 'seo-by-rank-math' ), value: 'daily', disabled: true },
|
||||
]
|
||||
|
||||
/**
|
||||
* AI Platform definitions.
|
||||
*
|
||||
* `enabled` — whether the platform is available for selection.
|
||||
* Disabled platforms show a "Coming Soon" badge.
|
||||
*
|
||||
* Layout: left column = index 0–2, right column = index 3–4.
|
||||
*/
|
||||
const AI_PLATFORMS = [
|
||||
{ id: 'chatgpt', label: 'ChatGPT', enabled: true },
|
||||
{ id: 'perplexity', label: 'Perplexity', enabled: false },
|
||||
{ id: 'google_ai_overview', label: 'Google AI Overview', enabled: false },
|
||||
{ id: 'gemini', label: 'Gemini', enabled: false },
|
||||
{ id: 'claude', label: 'Claude', enabled: false },
|
||||
]
|
||||
|
||||
const LEFT_PLATFORMS = AI_PLATFORMS.slice( 0, 3 )
|
||||
const RIGHT_PLATFORMS = AI_PLATFORMS.slice( 3 )
|
||||
const FIELD_ORDER = [ 'name', 'url', 'description', 'language' ]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sub-components
|
||||
@@ -114,12 +91,17 @@ const PlatformRow = ( { platform, checked, onChange, disabled } ) => {
|
||||
* AddBrandModal component.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {Object|null} [props.brand=null] null = add mode, object = edit (pre-fills form).
|
||||
* @param {Function} props.onSave Called with the validated form payload.
|
||||
* @param {Function} props.onClose Called when the modal should close.
|
||||
* @param {boolean} [props.isSaving=false] Shows spinner + disables all fields.
|
||||
* @param {string | null} props.apiError API error message to display.
|
||||
* @param {Array} [props.locales=[]] Locale options injected from PHP via wp_localize_script.
|
||||
* @param {Object|null} [props.brand=null] null = add mode, object = edit (pre-fills form).
|
||||
* @param {Function} props.onSave Called with the validated form payload.
|
||||
* @param {Function} props.onClose Called when the modal should close.
|
||||
* @param {boolean} [props.isSaving=false] Shows spinner + disables all fields.
|
||||
* @param {string | null} props.apiError API error message to display.
|
||||
* @param {Array} [props.locales=[]] Locale options injected from PHP via wp_localize_script.
|
||||
* @param {Array} [props.languages=[]] Output language options injected from PHP via wp_localize_script.
|
||||
* @param {string} [props.defaultLanguage=''] Default language for a new brand (site language), injected from PHP.
|
||||
* @param {Array} [props.intervals=[]] { label, value, disabled } options injected from PHP via wp_localize_script.
|
||||
* @param {Object} [props.platforms={}] AI platform registry injected from PHP.
|
||||
* @param {number} [props.maxPlatforms=1] Platforms selectable on the current plan.
|
||||
* @return {JSX.Element} Brand add/edit dialog.
|
||||
*/
|
||||
const AddBrandModal = ( {
|
||||
@@ -129,8 +111,16 @@ const AddBrandModal = ( {
|
||||
isSaving = false,
|
||||
apiError = null,
|
||||
locales = [],
|
||||
languages = [],
|
||||
defaultLanguage = '',
|
||||
intervals = [],
|
||||
platforms = {},
|
||||
maxPlatforms = 1,
|
||||
} ) => {
|
||||
const [ form, setForm ] = useState( EMPTY_FORM )
|
||||
const platformList = useMemo( () => toPlatformList( platforms ), [ platforms ] )
|
||||
const enabledPlatformCount = useMemo( () => getEnabledPlatformIds( platformList ).length, [ platformList ] )
|
||||
|
||||
const [ form, setForm ] = useState( () => emptyForm( platformList, defaultLanguage ) )
|
||||
const [ errors, setErrors ] = useState( {} )
|
||||
|
||||
const ns = 'rank-math-ai-visibility-add-brand-modal'
|
||||
@@ -140,6 +130,7 @@ const AddBrandModal = ( {
|
||||
name: useRef( null ),
|
||||
url: useRef( null ),
|
||||
description: useRef( null ),
|
||||
language: useRef( null ),
|
||||
}
|
||||
|
||||
// Locale options — object map expected by SelectWithSearch: { value: label, … }
|
||||
@@ -152,6 +143,14 @@ const AddBrandModal = ( {
|
||||
[ locales ]
|
||||
)
|
||||
|
||||
const languageOptions = useMemo(
|
||||
() => languages.reduce( ( acc, { name, icon } ) => {
|
||||
acc[ name ] = icon ? `${ icon } ${ name }` : name
|
||||
return acc
|
||||
}, {} ),
|
||||
[ languages ]
|
||||
)
|
||||
|
||||
// Pre-fill when editing.
|
||||
useEffect( () => {
|
||||
if ( brand ) {
|
||||
@@ -161,12 +160,17 @@ const AddBrandModal = ( {
|
||||
url: brand.url ?? '',
|
||||
description: brand.description ?? '',
|
||||
locale: brand.locale ?? '',
|
||||
interval: brand.interval ?? 'weekly',
|
||||
platforms: brand.platforms ?? [ 'chatgpt' ],
|
||||
// Legacy brands predate the language field.
|
||||
language: brand.language ?? 'US English',
|
||||
interval: brand.interval ?? 'monthly',
|
||||
platforms: brand.platforms?.length
|
||||
? brand.platforms.slice( 0, maxPlatforms )
|
||||
: getDefaultPlatforms( platformList ),
|
||||
} )
|
||||
} else {
|
||||
setForm( EMPTY_FORM )
|
||||
setForm( emptyForm( platformList, defaultLanguage ) )
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [ brand ] )
|
||||
|
||||
// ── Field helpers ────────────────────────────────────────────────────────
|
||||
@@ -184,18 +188,24 @@ const AddBrandModal = ( {
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle a platform ID in the platforms array.
|
||||
* Toggle a platform. Selecting past the plan cap evicts the oldest pick.
|
||||
*
|
||||
* @param {string} id Platform id to toggle.
|
||||
*/
|
||||
const togglePlatform = ( id ) => {
|
||||
setForm( ( prev ) => {
|
||||
const exists = prev.platforms.includes( id )
|
||||
if ( prev.platforms.includes( id ) ) {
|
||||
return {
|
||||
...prev,
|
||||
platforms: prev.platforms.filter( ( p ) => p !== id ),
|
||||
}
|
||||
}
|
||||
|
||||
const next = [ ...prev.platforms, id ]
|
||||
|
||||
return {
|
||||
...prev,
|
||||
platforms: exists
|
||||
? prev.platforms.filter( ( p ) => p !== id )
|
||||
: [ ...prev.platforms, id ],
|
||||
platforms: next.slice( Math.max( 0, next.length - maxPlatforms ) ),
|
||||
}
|
||||
} )
|
||||
}
|
||||
@@ -229,6 +239,9 @@ const AddBrandModal = ( {
|
||||
if ( ! form.description.trim() ) {
|
||||
newErrors.description = __( 'Description is required.', 'seo-by-rank-math' )
|
||||
}
|
||||
if ( ! form.language ) {
|
||||
newErrors.language = __( 'Language is required.', 'seo-by-rank-math' )
|
||||
}
|
||||
|
||||
setErrors( newErrors )
|
||||
return newErrors
|
||||
@@ -266,13 +279,14 @@ const AddBrandModal = ( {
|
||||
url: form.url.trim(),
|
||||
description: form.description.trim(),
|
||||
locale: form.locale,
|
||||
language: form.language,
|
||||
interval: form.interval,
|
||||
platforms: form.platforms,
|
||||
} )
|
||||
}
|
||||
|
||||
const isEditMode = Boolean( brand )
|
||||
const isActionDisabled = isSaving || form?.platforms?.length === 0 || Object.keys( errors ).length > 0
|
||||
const isActionDisabled = isSaving || form?.platforms?.length === 0 || ! form?.language || Object.keys( errors ).length > 0
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -370,12 +384,35 @@ const AddBrandModal = ( {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={ `${ ns }__field` } ref={ fieldRefs.language }>
|
||||
<span className={ `${ ns }__label` }>
|
||||
{ __( 'Output Language', 'seo-by-rank-math' ) }
|
||||
</span>
|
||||
<SelectWithSearch
|
||||
value={ form.language }
|
||||
options={ languageOptions }
|
||||
onChange={ set( 'language' ) }
|
||||
disabled={ isSaving || isEditMode }
|
||||
className={ errors.language ? `${ ns }__field--error` : '' }
|
||||
/>
|
||||
{ errors.language && (
|
||||
<p className={ `${ ns }__field-note ${ ns }__field-note--error` }>
|
||||
{ errors.language }
|
||||
</p>
|
||||
) }
|
||||
{ isEditMode && (
|
||||
<p className={ `${ ns }__field-note` }>
|
||||
{ __( 'Language can\'t be changed after a brand is created.', 'seo-by-rank-math' ) }
|
||||
</p>
|
||||
) }
|
||||
</div>
|
||||
|
||||
{ /* Interval */ }
|
||||
<div className={ `${ ns }__field` }>
|
||||
<SelectControl
|
||||
label={ __( 'Frequency of analyses', 'seo-by-rank-math' ) }
|
||||
value={ form.interval }
|
||||
options={ INTERVAL_OPTIONS }
|
||||
options={ intervals }
|
||||
onChange={ set( 'interval' ) }
|
||||
disabled={ isSaving }
|
||||
__next40pxDefaultSize={ true }
|
||||
@@ -388,29 +425,35 @@ const AddBrandModal = ( {
|
||||
<span className={ `${ ns }__label` }>
|
||||
{ __( 'AI Platforms', 'seo-by-rank-math' ) }
|
||||
</span>
|
||||
{ maxPlatforms < enabledPlatformCount && (
|
||||
<p className={ `${ ns }__field-note` }>
|
||||
{ sprintf(
|
||||
/* translators: %d: number of AI platforms selectable on the current plan. */
|
||||
_n(
|
||||
'Your plan lets you track %d platform per brand. Upgrade to Expert to track them all at once.',
|
||||
'Your plan lets you track %d platforms per brand. Upgrade to Expert to track them all at once.',
|
||||
maxPlatforms,
|
||||
'seo-by-rank-math'
|
||||
),
|
||||
maxPlatforms
|
||||
) }
|
||||
</p>
|
||||
) }
|
||||
{ form.platforms.length === 0 && (
|
||||
<p className={ `${ ns }__field-note ${ ns }__field-note--error` }>
|
||||
{ __( 'Select at least one AI platform.', 'seo-by-rank-math' ) }
|
||||
</p>
|
||||
) }
|
||||
<div className={ `${ ns }__platforms` }>
|
||||
<div className={ `${ ns }__platforms-col` }>
|
||||
{ LEFT_PLATFORMS.map( ( platform ) => (
|
||||
<PlatformRow
|
||||
key={ platform.id }
|
||||
platform={ platform }
|
||||
checked={ form.platforms.includes( platform.id ) }
|
||||
onChange={ () => togglePlatform( platform.id ) }
|
||||
disabled={ isSaving }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
<div className={ `${ ns }__platforms-col` }>
|
||||
{ RIGHT_PLATFORMS.map( ( platform ) => (
|
||||
<PlatformRow
|
||||
key={ platform.id }
|
||||
platform={ platform }
|
||||
checked={ form.platforms.includes( platform.id ) }
|
||||
onChange={ () => togglePlatform( platform.id ) }
|
||||
disabled={ isSaving }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
{ platformList.map( ( platform ) => (
|
||||
<PlatformRow
|
||||
key={ platform.id }
|
||||
platform={ platform }
|
||||
checked={ form.platforms.includes( platform.id ) }
|
||||
onChange={ () => togglePlatform( platform.id ) }
|
||||
disabled={ isSaving }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+11
-6
@@ -132,6 +132,16 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
&__field-note {
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: $color-text-muted;
|
||||
|
||||
&--error {
|
||||
color: $color-trend-down;
|
||||
}
|
||||
}
|
||||
|
||||
.components-base-control__label,
|
||||
.components-input-control__label {
|
||||
font-size: 11px;
|
||||
@@ -186,16 +196,11 @@
|
||||
&__platforms {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-auto-flow: row;
|
||||
gap: 10px 16px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
&__platforms-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
&__platform-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ import './StatCard.scss'
|
||||
* @return {JSX.Element} Stat card with icon, label, value, and optional trend.
|
||||
*/
|
||||
const StatCard = ( { icon, label, value, tooltip, sub, compact = false, className = '', analysis = null } ) => {
|
||||
const hasData = ( analysis?.status && analysis?.status === 'done' ) ?? ( value !== null && value !== undefined && value !== '' && value !== '—' )
|
||||
const hasData = ( analysis?.status && ( analysis?.status === 'done' || analysis?.status === 'partial' ) ) ?? ( value !== null && value !== undefined && value !== '' && value !== '—' )
|
||||
|
||||
const ns = 'rank-math-ai-visibility-stat-card'
|
||||
|
||||
|
||||
+4
@@ -173,6 +173,10 @@ const TranscriptViewer = ( {
|
||||
if ( e.query ) {
|
||||
label = e.query.length > 60 ? e.query.slice( 0, 60 ) + '…' : e.query
|
||||
}
|
||||
// Append platform — multiple platforms can share the same query text.
|
||||
if ( e.platform ) {
|
||||
label += ` — ${ e.platform }`
|
||||
}
|
||||
return { label, value: String( e.id ) }
|
||||
} ),
|
||||
], [ entries ] )
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* usePagination — client-side pagination over an in-memory array.
|
||||
*
|
||||
* @since 1.0.274
|
||||
*/
|
||||
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { useState, useMemo, useCallback, useEffect, useRef } from '@wordpress/element'
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { getPageFromUrl, getPerPageFromUrl, writePaginationToUrl } from '../../utils/urlState'
|
||||
|
||||
const DEFAULT_PER_PAGE = 10
|
||||
|
||||
/**
|
||||
* @param {Array} items Full, already-filtered item list to paginate.
|
||||
* @param {Object} [options]
|
||||
* @param {number} [options.perPage=10] Default/initial page size.
|
||||
* @param {boolean} [options.syncUrl=false] Read the initial page from the URL and keep it updated.
|
||||
* @return {Object} `{ pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage }`
|
||||
*/
|
||||
const usePagination = ( items = [], { perPage = DEFAULT_PER_PAGE, syncUrl = false } = {} ) => {
|
||||
const [ pagination, setPagination ] = useState( () => ( {
|
||||
page: syncUrl ? getPageFromUrl( 1 ) : 1,
|
||||
perPage: syncUrl ? getPerPageFromUrl( perPage ) : perPage,
|
||||
} ) )
|
||||
|
||||
const total = items.length
|
||||
const pages = Math.max( 1, Math.ceil( total / pagination.perPage ) )
|
||||
|
||||
const pageItems = useMemo( () => {
|
||||
const offset = ( pagination.page - 1 ) * pagination.perPage
|
||||
return items.slice( offset, offset + pagination.perPage )
|
||||
}, [ items, pagination ] )
|
||||
|
||||
// Clamp out-of-range pages, but not on mount (would clobber a URL-provided page).
|
||||
const isFirstRun = useRef( true )
|
||||
useEffect( () => {
|
||||
if ( isFirstRun.current ) {
|
||||
isFirstRun.current = false
|
||||
return
|
||||
}
|
||||
setPagination( ( prev ) => ( prev.page > pages ? { ...prev, page: pages } : prev ) )
|
||||
}, [ pages ] )
|
||||
|
||||
useEffect( () => {
|
||||
if ( syncUrl ) {
|
||||
writePaginationToUrl( pagination, perPage )
|
||||
}
|
||||
}, [ pagination, syncUrl, perPage ] )
|
||||
|
||||
const onPageChange = useCallback(
|
||||
( page ) => setPagination( ( prev ) => ( { ...prev, page: Math.max( 1, page ) } ) ),
|
||||
[]
|
||||
)
|
||||
|
||||
const onPerPageChange = useCallback(
|
||||
( newPerPage ) => setPagination( { page: 1, perPage: Math.max( 1, newPerPage ) } ),
|
||||
[]
|
||||
)
|
||||
|
||||
const resetPage = useCallback(
|
||||
() => setPagination( ( prev ) => ( prev.page === 1 ? prev : { ...prev, page: 1 } ) ),
|
||||
[]
|
||||
)
|
||||
|
||||
return { pagination, pageItems, total, pages, onPageChange, onPerPageChange, resetPage }
|
||||
}
|
||||
|
||||
export default usePagination
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* AI platform registry helpers — mirrors `Platforms` in PHP.
|
||||
*
|
||||
* @since 1.0.275
|
||||
*/
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { map, filter } from 'lodash'
|
||||
|
||||
/**
|
||||
* Convert the localized registry map into a list, preserving key order.
|
||||
*
|
||||
* @param {Object} platforms Registry keyed by platform ID.
|
||||
* @return {Array<{id: string, label: string, enabled: boolean}>} Platform list.
|
||||
*/
|
||||
export const toPlatformList = ( platforms = {} ) =>
|
||||
map( platforms, ( platform, id ) => ( {
|
||||
id,
|
||||
label: platform?.label ?? id,
|
||||
enabled: Boolean( platform?.enabled ),
|
||||
} ) )
|
||||
|
||||
/**
|
||||
* Platform IDs available for selection.
|
||||
*
|
||||
* @param {Array} platformList Output of toPlatformList().
|
||||
* @return {string[]} Enabled platform IDs.
|
||||
*/
|
||||
export const getEnabledPlatformIds = ( platformList = [] ) =>
|
||||
map( filter( platformList, 'enabled' ), 'id' )
|
||||
|
||||
/**
|
||||
* Default selection for a new brand — the first enabled platform.
|
||||
*
|
||||
* @param {Array} platformList Output of toPlatformList().
|
||||
* @return {string[]} Default platform IDs.
|
||||
*/
|
||||
export const getDefaultPlatforms = ( platformList = [] ) =>
|
||||
getEnabledPlatformIds( platformList ).slice( 0, 1 )
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
* Derive a brand's display analysis state from its `analysis_status`.
|
||||
*
|
||||
* API status semantics:
|
||||
* success → ran successfully (a future weekly run is masked as success)
|
||||
* success → ran successfully (a future monthly run is masked as success)
|
||||
* partial → last run completed partially
|
||||
* pending → awaiting first run, or an overdue run is due
|
||||
* running → a run is currently in progress
|
||||
|
||||
+30
@@ -110,3 +110,33 @@ export const navigateToReportsTab = ( brandId ) => {
|
||||
window.history.pushState( {}, '', url )
|
||||
window.dispatchEvent( new window.PopStateEvent( 'popstate' ) )
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} [fallback=1] Fallback when `aiv_page` is absent/invalid.
|
||||
* @return {number} Page number from the URL.
|
||||
*/
|
||||
export const getPageFromUrl = ( fallback = 1 ) => {
|
||||
const raw = parseInt( getQueryArg( window.location.href, 'aiv_page' ), 10 )
|
||||
return raw > 0 ? raw : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} [fallback=10] Fallback when `aiv_per` is absent/invalid.
|
||||
* @return {number} Page size from the URL.
|
||||
*/
|
||||
export const getPerPageFromUrl = ( fallback = 10 ) => {
|
||||
const raw = parseInt( getQueryArg( window.location.href, 'aiv_per' ), 10 )
|
||||
return raw > 0 ? raw : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} pagination `{ page, perPage }`.
|
||||
* @param {number} [defaultPerPage=10] Omitted from the URL when matched.
|
||||
*/
|
||||
export const writePaginationToUrl = ( pagination, defaultPerPage = 10 ) => {
|
||||
const url = addQueryArgs( window.location.href, {
|
||||
aiv_page: pagination.page > 1 ? pagination.page : undefined,
|
||||
aiv_per: pagination.perPage !== defaultPerPage ? pagination.perPage : undefined,
|
||||
} )
|
||||
window.history.replaceState( {}, '', url )
|
||||
}
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
/**
|
||||
* AI platform registry.
|
||||
*
|
||||
* @since 1.0.275
|
||||
* @package RankMath
|
||||
* @subpackage RankMath\AI_Visibility
|
||||
* @author Rank Math <support@rankmath.com>
|
||||
*/
|
||||
|
||||
namespace RankMath\AI_Visibility;
|
||||
|
||||
use WP_Error;
|
||||
use RankMath\Helper;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Platforms class.
|
||||
*/
|
||||
final class Platforms {
|
||||
|
||||
/**
|
||||
* Plan that unlocks every supported platform.
|
||||
*/
|
||||
const UNLIMITED_PLAN = 'expert';
|
||||
|
||||
/**
|
||||
* Platform definitions. Key order drives the UI column split.
|
||||
*
|
||||
* @var array<string, array{label: string, enabled: bool}>
|
||||
*/
|
||||
private const PLATFORMS = [
|
||||
'chatgpt' => [
|
||||
'label' => 'ChatGPT',
|
||||
'enabled' => true,
|
||||
],
|
||||
'gemini' => [
|
||||
'label' => 'Google Gemini',
|
||||
'enabled' => true,
|
||||
],
|
||||
'perplexity' => [
|
||||
'label' => 'Perplexity',
|
||||
'enabled' => false,
|
||||
],
|
||||
'claude' => [
|
||||
'label' => 'Claude',
|
||||
'enabled' => false,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Every known platform, keyed by ID.
|
||||
*
|
||||
* @return array<string, array{label: string, enabled: bool}>
|
||||
*/
|
||||
public static function all() {
|
||||
return self::PLATFORMS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Platform IDs available for selection.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function supported() {
|
||||
return array_keys(
|
||||
array_filter(
|
||||
self::PLATFORMS,
|
||||
function ( $platform ) {
|
||||
return ! empty( $platform['enabled'] );
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Platforms the current plan may track per brand.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function max_selectable() {
|
||||
return self::UNLIMITED_PLAN === Helper::get_content_ai_plan()
|
||||
? count( self::supported() )
|
||||
: 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Supported IDs as a quoted list, e.g. `"chatgpt", "gemini"`.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function supported_as_string() {
|
||||
return implode(
|
||||
', ',
|
||||
array_map(
|
||||
function ( $id ) {
|
||||
return '"' . $id . '"';
|
||||
},
|
||||
self::supported()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* REST route arg definition for a `platforms` param.
|
||||
*
|
||||
* @param bool $required Whether the param is mandatory.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function rest_arg( $required ) {
|
||||
return [
|
||||
'description' => sprintf(
|
||||
/* translators: %s: supported platform IDs. */
|
||||
esc_html__( 'AI platforms to track for this brand. Supported values: %s. Tracking more than one platform per brand requires the Expert plan.', 'seo-by-rank-math' ),
|
||||
self::supported_as_string()
|
||||
),
|
||||
'type' => 'array',
|
||||
'minItems' => 1,
|
||||
'items' => [
|
||||
'type' => 'string',
|
||||
'enum' => self::supported(),
|
||||
],
|
||||
'required' => $required,
|
||||
'validate_callback' => [ self::class, 'validate' ],
|
||||
'sanitize_callback' => [ self::class, 'sanitize' ],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize, dedupe and drop unsupported IDs.
|
||||
*
|
||||
* @param mixed $value Raw platforms value.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function sanitize( $value ) {
|
||||
return array_values(
|
||||
array_unique(
|
||||
array_intersect(
|
||||
array_map( 'sanitize_text_field', (array) $value ),
|
||||
self::supported()
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate against the registry and the plan limit.
|
||||
*
|
||||
* @param mixed $value Raw platforms value.
|
||||
*
|
||||
* @return true|WP_Error
|
||||
*/
|
||||
public static function validate( $value ) {
|
||||
if ( null === $value || '' === $value || [] === $value ) {
|
||||
return new WP_Error(
|
||||
'aiv_bad_request',
|
||||
sprintf(
|
||||
/* translators: %s: supported platform IDs. */
|
||||
esc_html__( 'Please specify which AI platforms to track. Supported values: %s.', 'seo-by-rank-math' ),
|
||||
self::supported_as_string()
|
||||
),
|
||||
[ 'status' => 400 ]
|
||||
);
|
||||
}
|
||||
|
||||
$platforms = self::sanitize( $value );
|
||||
|
||||
if ( empty( $platforms ) ) {
|
||||
return new WP_Error(
|
||||
'aiv_bad_request',
|
||||
sprintf(
|
||||
/* translators: %s: supported platform IDs. */
|
||||
esc_html__( 'No valid AI platforms were provided. Supported values: %s.', 'seo-by-rank-math' ),
|
||||
self::supported_as_string()
|
||||
),
|
||||
[ 'status' => 400 ]
|
||||
);
|
||||
}
|
||||
|
||||
$max = self::max_selectable();
|
||||
if ( count( $platforms ) > $max ) {
|
||||
return new WP_Error(
|
||||
'aiv_plan_limit',
|
||||
sprintf(
|
||||
/* translators: 1: platforms allowed on the current plan, 2: supported platform IDs. */
|
||||
esc_html__( 'Your plan allows tracking %1$d AI platform(s) per brand — upgrade to the Expert plan to track more. Supported values: %2$s.', 'seo-by-rank-math' ),
|
||||
$max,
|
||||
self::supported_as_string()
|
||||
),
|
||||
[ 'status' => 403 ]
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -133,26 +133,6 @@ class Watcher {
|
||||
* @return string
|
||||
*/
|
||||
public function get_permalink( $post_id ) {
|
||||
$permalink = get_permalink( $post_id );
|
||||
|
||||
if ( ! Sitepress::get()->is_active() ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
$sitepress = Sitepress::get()->get_var();
|
||||
|
||||
$language_domains = $sitepress->get_setting( 'language_domains', [] );
|
||||
if ( ! $language_domains ) {
|
||||
return $permalink;
|
||||
}
|
||||
|
||||
$details = apply_filters( 'wpml_post_language_details', null, $post_id );
|
||||
$code = $details['language_code'] ?? '';
|
||||
$permalink = apply_filters( 'wpml_permalink', get_the_permalink( $post_id ), $code );
|
||||
foreach ( $language_domains as $key => $domain ) {
|
||||
$permalink = preg_replace( "#https?://{$domain}#i", '', $permalink );
|
||||
}
|
||||
|
||||
return $permalink;
|
||||
return Sitepress::get()->get_permalink( $post_id );
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
-1
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
+4
-4
@@ -35,8 +35,8 @@ const getErrorMessage = () => {
|
||||
if ( ! rankMath.contentAI.plan ) {
|
||||
return (
|
||||
<>
|
||||
{ __( 'You do not have a Content AI plan.', 'seo-by-rank-math' ) }
|
||||
<a href="https://rankmath.com/kb/how-to-use-content-ai/?play-video=ioPeVIntJWw&utm_source=Plugin&utm_medium=Buy+Plan+Button&utm_campaign=WP">
|
||||
{ __( 'You do not have a Rank Math AI plan.', 'seo-by-rank-math' ) }
|
||||
<a href="https://rankmath.com/ai/pricing/?utm_source=Plugin&utm_medium=Buy+Plan+Button&utm_campaign=WP">
|
||||
{ __( 'Choose your plan', 'seo-by-rank-math' ) }
|
||||
</a>
|
||||
</>
|
||||
@@ -45,8 +45,8 @@ const getErrorMessage = () => {
|
||||
|
||||
return (
|
||||
<>
|
||||
{ __( 'You have exhausted your Content AI Credits.', 'seo-by-rank-math' ) }
|
||||
<a href="https://rankmath.com/kb/how-to-use-content-ai/?play-video=ioPeVIntJWw&utm_source=Plugin&utm_medium=Buy+Credits+Button&utm_campaign=WP" target="_blank" rel="noreferrer">
|
||||
{ __( 'You have exhausted your Rank Math AI Usage.', 'seo-by-rank-math' ) }
|
||||
<a href="https://rankmath.com/ai/pricing/?utm_source=Plugin&utm_medium=Buy+Credits+Button&utm_campaign=WP" target="_blank" rel="noreferrer">
|
||||
{ __( 'Get more', 'seo-by-rank-math' ) }
|
||||
</a>
|
||||
</>
|
||||
|
||||
@@ -142,7 +142,7 @@ class Admin {
|
||||
$refresh_date = Helper::get_content_ai_refresh_date();
|
||||
$content_ai = [
|
||||
'ca_plan' => [
|
||||
'label' => esc_html__( 'Content AI Plan', 'seo-by-rank-math' ),
|
||||
'label' => esc_html__( 'Rank Math AI Plan', 'seo-by-rank-math' ),
|
||||
'value' => \ucwords( Helper::get_content_ai_plan() ),
|
||||
],
|
||||
'ca_credits' => [
|
||||
|
||||
@@ -69,6 +69,7 @@ class Content_AI {
|
||||
'audience' => (array) Helper::get_settings( 'general.content_ai_audience', 'General Audience' ),
|
||||
'tone' => (array) Helper::get_settings( 'general.content_ai_tone', 'Formal' ),
|
||||
'language' => Helper::get_settings( 'general.content_ai_language', Helper::content_ai_default_language() ),
|
||||
'languages' => Helper::get_content_ai_languages(),
|
||||
'history' => Helper::get_outputs(),
|
||||
'chats' => Helper::get_chats(),
|
||||
'recentPrompts' => Helper::get_recent_prompts(),
|
||||
|
||||
@@ -212,7 +212,7 @@ class Rest extends WP_REST_Controller {
|
||||
'permission_callback' => [ $this, 'has_ping_permission' ],
|
||||
'args' => [
|
||||
'plan' => [
|
||||
'description' => esc_html__( 'Content AI plan to update in the Database.', 'seo-by-rank-math' ),
|
||||
'description' => esc_html__( 'Rank Math AI plan to update in the Database.', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'required' => true,
|
||||
],
|
||||
@@ -675,7 +675,7 @@ class Rest extends WP_REST_Controller {
|
||||
return wp_kses_post(
|
||||
sprintf(
|
||||
// Translators: link to the update page.
|
||||
__( 'There is a new version of Content AI available! %s the Rank Math SEO plugin to use this feature.', 'seo-by-rank-math' ),
|
||||
__( 'There is a new version of Rank Math AI available! %s the Rank Math SEO plugin to use this feature.', 'seo-by-rank-math' ),
|
||||
'<a href="' . esc_url( self_admin_url( 'update-core.php' ) ) . '">' . __( 'Please update', 'seo-by-rank-math' ) . '</a>'
|
||||
)
|
||||
);
|
||||
|
||||
+3
-4
@@ -326,14 +326,13 @@ class Instant_Indexing extends Base {
|
||||
}
|
||||
|
||||
if ( Sitepress::get()->is_active() ) {
|
||||
$details = apply_filters( 'wpml_post_language_details', null, $post_id );
|
||||
$code = $details['language_code'] ?? '';
|
||||
$url = apply_filters( 'wpml_permalink', get_the_permalink( $post_id ), $code );
|
||||
$url = Sitepress::get()->get_permalink( $post_id );
|
||||
|
||||
$sitepress = Sitepress::get()->get_var();
|
||||
$urls = $sitepress->get_setting( 'urls' );
|
||||
if ( isset( $urls['directory_for_default_language'] ) && $urls['directory_for_default_language'] ) {
|
||||
$lang = $sitepress->get_current_language();
|
||||
$details = apply_filters( 'wpml_post_language_details', null, $post_id );
|
||||
$lang = $details['language_code'] ?? $sitepress->get_current_language();
|
||||
if ( 0 !== strpos( $url, '/' . $lang ) ) {
|
||||
$url = get_home_url() . $post->post_name;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -152,26 +152,29 @@ class LLMS_Txt {
|
||||
* @return void
|
||||
*/
|
||||
private function add_header_content() {
|
||||
$site_title = Helper::get_settings( 'titles.knowledgegraph_name', get_bloginfo( 'name' ) );
|
||||
$site_desc = Helper::get_settings( 'titles.organization_description', get_bloginfo( 'description' ) );
|
||||
$site_title .= $site_desc ? ': ' . $site_desc : '';
|
||||
|
||||
if ( ! $this->do_filter( 'llms_txt/remove_credit', false ) ) {
|
||||
$this->output_line( 'Generated by Rank Math SEO, this is an llms.txt file designed to help LLMs better understand and index this website.' );
|
||||
$this->output_line( '' );
|
||||
}
|
||||
|
||||
$this->output_line( '# ' . esc_html( $site_title ) );
|
||||
$site_title = $this->format_text( Helper::get_settings( 'titles.knowledgegraph_name', get_bloginfo( 'name' ) ) );
|
||||
$summary = $this->format_text( Helper::replace_vars( Helper::get_settings( 'general.llms_summary', '' ) ) );
|
||||
|
||||
$this->output_line( '# ' . $site_title );
|
||||
$this->output_line( '' );
|
||||
|
||||
if ( $summary ) {
|
||||
$this->output_line( '> ' . $summary );
|
||||
$this->output_line( '' );
|
||||
}
|
||||
|
||||
if ( ! Helper::is_module_active( 'sitemap' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->output_line( '' );
|
||||
$sitemap_url = Router::get_base_url( Sitemap::get_sitemap_index_slug() . '.xml' );
|
||||
$this->output_line( '## Sitemaps' );
|
||||
$this->output_line( '[XML Sitemap](' . esc_url( $sitemap_url ) . '): Includes all crawlable and indexable pages.' );
|
||||
// Add an extra blank line after the header content.
|
||||
$this->output_line( '- [XML Sitemap](' . esc_url_raw( $sitemap_url ) . '): Includes all crawlable and indexable pages.' );
|
||||
$this->output_line( '' );
|
||||
}
|
||||
|
||||
@@ -219,16 +222,16 @@ class LLMS_Txt {
|
||||
continue;
|
||||
}
|
||||
|
||||
$label = get_post_type_object( $post_type )->labels->name;
|
||||
$this->output_line( '## ' . esc_html( $label ) );
|
||||
$label = $this->format_text( get_post_type_object( $post_type )->labels->name );
|
||||
$this->output_line( '## ' . $label );
|
||||
|
||||
foreach ( $posts as $object ) {
|
||||
if ( ! Helper::is_post_indexable( $object ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$title = get_the_title( $object );
|
||||
$link = get_permalink( $object );
|
||||
$title = $this->format_text( get_the_title( $object ) );
|
||||
$link = esc_url_raw( get_permalink( $object ) );
|
||||
$object->post_content = do_shortcode( $object->post_content );
|
||||
$desc = Helper::replace_vars( '%excerpt%', $object );
|
||||
|
||||
@@ -240,12 +243,12 @@ class LLMS_Txt {
|
||||
* @param \WP_Post $object The post object.
|
||||
* @return string Modified description.
|
||||
*/
|
||||
$desc = wp_strip_all_tags( $this->do_filter( 'llms_txt/post_description', $desc, $object ) );
|
||||
$desc = $this->format_text( $this->do_filter( 'llms_txt/post_description', $desc, $object ) );
|
||||
|
||||
$this->output_line(
|
||||
$desc
|
||||
? '- [' . esc_html( $title ) . '](' . esc_url( $link ) . '): ' . esc_html( $desc )
|
||||
: '- [' . esc_html( $title ) . '](' . esc_url( $link ) . ')'
|
||||
? '- [' . $title . '](' . $link . '): ' . $desc
|
||||
: '- [' . $title . '](' . $link . ')'
|
||||
);
|
||||
}
|
||||
$this->output_line( '' );
|
||||
@@ -291,13 +294,19 @@ class LLMS_Txt {
|
||||
continue;
|
||||
}
|
||||
|
||||
$label = $tax_obj->labels->name;
|
||||
$this->output_line( '## ' . esc_html( $label ) );
|
||||
$label = $this->format_text( $tax_obj->labels->name );
|
||||
$this->output_line( '## ' . $label );
|
||||
foreach ( $terms as $term ) {
|
||||
if ( $term && Helper::is_term_indexable( $term ) ) {
|
||||
$name = $term->name;
|
||||
$link = get_term_link( $term );
|
||||
$this->output_line( '- [' . esc_html( $name ) . '](' . esc_url( $link ) . ')' );
|
||||
$name = $this->format_text( $term->name );
|
||||
$link = esc_url_raw( get_term_link( $term ) );
|
||||
$desc = $this->format_text( $term->description );
|
||||
|
||||
$this->output_line(
|
||||
$desc
|
||||
? '- [' . $name . '](' . $link . '): ' . $desc
|
||||
: '- [' . $name . '](' . $link . ')'
|
||||
);
|
||||
}
|
||||
}
|
||||
$this->output_line( '' );
|
||||
@@ -319,17 +328,28 @@ class LLMS_Txt {
|
||||
*/
|
||||
$extra = $this->do_filter( 'llms_txt/extra_content', Helper::get_settings( 'general.llms_extra_content', '' ) );
|
||||
if ( ! empty( $extra ) ) {
|
||||
$this->output_line( esc_html( str_replace( "\n", "\n", $extra ) ) );
|
||||
$this->output_line( $this->format_text( $extra ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs a line with a newline character (\n).
|
||||
* Normalizes text for plain-text output: strips tags, decodes entities.
|
||||
* Decode first, so an entity-encoded tag (e.g. <script>) can't survive stripping.
|
||||
*
|
||||
* @param string $content The content to output.
|
||||
* @param string $text The text to normalize.
|
||||
* @return string Normalized plain text.
|
||||
*/
|
||||
private function format_text( $text ) {
|
||||
return trim( wp_strip_all_tags( html_entity_decode( (string) $text, ENT_QUOTES, 'UTF-8' ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs a line with a trailing newline.
|
||||
*
|
||||
* @param string $content Plain text content; must already be sanitized (see format_text()).
|
||||
* @return void
|
||||
*/
|
||||
private function output_line( $content ) {
|
||||
echo esc_html( $content ) . "\n";
|
||||
echo $content . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Plain text, not HTML; see format_text().
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -271,7 +271,7 @@ class Post_Type implements Provider {
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function get_post_type_count( $post_types ) {
|
||||
public function get_post_type_count( $post_types ) {
|
||||
global $wpdb;
|
||||
|
||||
$posts_to_exclude = 'page' === $post_types ? $this->get_blog_page_id() : '';
|
||||
|
||||
+1
-1
@@ -237,7 +237,7 @@ class Taxonomy implements Provider {
|
||||
* @param int $current_page Current page of the sitemap.
|
||||
* @return false|array
|
||||
*/
|
||||
private function get_terms( $taxonomy, $max_entries, $current_page ) {
|
||||
public function get_terms( $taxonomy, $max_entries, $current_page ) {
|
||||
$offset = $current_page > 1 ? ( ( $current_page - 1 ) * $max_entries ) : 0;
|
||||
$hide_empty = ! Helper::get_settings( 'sitemap.tax_' . $taxonomy->name . '_include_empty' );
|
||||
|
||||
|
||||
Reference in New Issue
Block a user