Initial commit xmarticaims

This commit is contained in:
2026-11-02 10:26:32 -06:00
commit e74236f5c1
9764 changed files with 2880647 additions and 0 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,60 @@
<?php
/**
* Divi admin integration.
*
* @package RankMath
* @subpackage RankMath\Core
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Divi;
use RankMath\Traits\Hooker;
defined( 'ABSPATH' ) || exit;
/**
* Divi class.
*/
class Divi_Admin {
use Hooker;
/**
* Class constructor.
*/
public function __construct() {
$this->init();
}
/**
* Initialize Divi admin.
*/
public function init() {
$screen = get_current_screen();
if ( 'toplevel_page_et_divi_options' === $screen->id ) {
$this->action( 'admin_enqueue_scripts', 'enqueue_divi_admin_scripts' );
}
}
/**
* Enqueue scripts for Divi admin options screen.
*/
public function enqueue_divi_admin_scripts() {
wp_enqueue_script(
'rank-math-divi-admin',
rank_math()->plugin_url() . 'includes/3rdparty/divi/assets/js/divi-admin.js',
[
'jquery',
'react',
'react-dom',
'wp-components',
'wp-element',
'wp-i18n',
'wp-polyfill',
],
rank_math()->version,
true
);
}
}
@@ -0,0 +1,380 @@
<?php
/**
* Divi integration.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Core
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Divi;
use RankMath\KB;
use RankMath\Helper;
use RankMath\Helpers\Editor;
use RankMath\Helpers\Str;
use RankMath\Schema\DB as Schema_DB;
use RankMath\Schema\Admin as Schema_Admin;
use RankMath\Traits\Hooker;
use RankMath\Admin\Metabox\Screen;
use WP_Dependencies;
defined( 'ABSPATH' ) || exit;
/**
* Divi class.
*/
class Divi {
use Hooker;
/**
* Screen object.
*
* @var Screen
*/
private $screen;
/**
* Class constructor.
*/
public function __construct() {
$this->action( 'wp', 'init' );
}
/**
* Initialize.
*/
public function init() {
if ( ! $this->can_add_seo_tab() ) {
return;
}
$this->screen = new Screen();
$this->screen->load_screen( 'post' );
$this->action( 'template_redirect', 'set_window_lodash', 0 );
$this->action( 'wp_enqueue_scripts', 'register_rankmath_react' );
$this->action( 'wp_enqueue_scripts', 'add_json_data', 0 );
$this->action( 'wp_footer', 'footer_enqueue_scripts', 11 );
remove_action( 'wp_footer', [ rank_math()->json, 'output' ], 0 );
add_action( 'wp_footer', [ rank_math()->json, 'output' ], 11 );
$this->filter( 'script_loader_tag', 'add_et_tag', 10, 3 );
}
/**
* Set the global lodash variable.
*
* Lodash's `noConflict` would prevent UnderscoreJS from taking over the underscore (_)
* global variable. Because Underscore.js will later also be assigned to the underscore (_)
* global this function should run as early as possible.
*/
public function set_window_lodash() {
wp_register_script( 'rm-set-window-lodash', '', [ 'lodash' ], rank_math()->version, false );
wp_enqueue_script( 'rm-set-window-lodash' );
wp_add_inline_script(
'rm-set-window-lodash',
join(
"\r\n ",
[
'window.isLodash = function() {',
"if ( typeof window._ !== 'function' || typeof window._.forEach !== 'function' ) {",
'return false;',
'}',
'var isLodash = true;',
'window._.forEach(',
"[ 'cloneDeep', 'at', 'add', 'ary', 'attempt' ],",
'function( fn ) {',
"if ( isLodash && typeof window._[ fn ] !== 'function' ) {",
'isLodash = false;',
'}',
'}',
');',
'return isLodash;',
'}',
'if ( window.isLodash() ) { window.lodash = window._.noConflict(); }',
]
)
);
}
/**
* Register RankMath React and ReactDOM.
*
* Registers the native WP version of react with a custom handle for use in the
* RankMath module. Divi builder dequeues and deregisters native WP react scripts
* and replaces them with their own copy of React. Their copy might not be of the
* same version as the one RankMath requires.
*/
public function register_rankmath_react() {
$path = site_url( '/wp-includes/js/dist/vendor/' );
$suffix = wp_scripts_get_suffix();
wp_register_script( 'rm-react', "{$path}react{$suffix}.js", [ 'wp-polyfill', 'react' ], '16.13.1', true );
wp_register_script( 'rm-react-dom', "{$path}react-dom{$suffix}.js", [ 'rm-react', 'react-dom' ], '16.13.1', true );
}
/**
* Add JSON data.
*/
public function add_json_data() {
$this->maybe_load_editor_deps();
if ( Helper::has_cap( 'onpage_snippet' ) ) {
// Schema.
$schemas = $this->get_schema_data( get_the_ID() );
Helper::add_json( 'schemas', $schemas );
Helper::add_json( 'customSchemaImage', esc_url( rank_math()->plugin_url() . 'includes/modules/schema/assets/img/custom-schema-builder.jpg' ) );
// Trends.
$trends_upgrade_link = KB::get( 'pro', 'Divi General Tab Trends' );
Helper::add_json( 'trendsUpgradeLink', esc_url_raw( $trends_upgrade_link ) );
Helper::add_json( 'trendsPreviewImage', esc_url( rank_math()->plugin_url() . 'assets/admin/img/trends-preview.jpg' ) );
}
Helper::add_json(
'api',
[
'root' => esc_url_raw( get_rest_url() ),
'nonce' => ( wp_installing() && ! is_multisite() ) ? '' : wp_create_nonce( 'wp_rest' ),
]
);
Helper::add_json(
'keywordsApi',
[
'url' => 'https://api.rankmath.com/ltkw/v1/',
]
);
Helper::add_json( 'links', KB::get_links() );
Helper::add_json(
'validationl10n',
[
'regexErrorDefault' => __( 'Please use the correct format.', 'seo-by-rank-math' ),
'requiredErrorDefault' => __( 'This field is required.', 'seo-by-rank-math' ),
'emailErrorDefault' => __( 'Please enter a valid email address.', 'seo-by-rank-math' ),
'urlErrorDefault' => __( 'Please enter a valid URL.', 'seo-by-rank-math' ),
]
);
Helper::add_json( 'capitalizeTitle', Helper::get_settings( 'titles.capitalize_titles' ) );
Helper::add_json( 'blogName', get_bloginfo( 'name' ) );
if ( is_admin_bar_showing() && Helper::has_cap( 'admin_bar' ) ) {
Helper::add_json( 'objectID', get_the_ID() );
Helper::add_json( 'objectType', 'post' );
}
}
/**
* Enqueue scripts.
*/
public function footer_enqueue_scripts() {
/**
* Allow other plugins to enqueue/dequeue admin styles or scripts before plugin assets.
*/
$this->do_action( 'admin/before_editor_scripts' );
$divi_deps = [
'jquery',
'lodash',
'rm-react',
'rm-react-dom',
'rm-set-window-lodash',
'et-dynamic-asset-helpers',
'wp-api-fetch',
'wp-block-editor',
'wp-components',
'wp-compose',
'wp-core-data',
'wp-data',
'wp-element',
'wp-hooks',
'wp-media-utils',
'wp-wordcount',
'rank-math-analyzer',
'rank-math-app',
];
if ( is_admin_bar_showing() && Helper::has_cap( 'admin_bar' ) ) {
wp_enqueue_style( 'rank-math', rank_math()->assets() . 'css/rank-math.css', null, rank_math()->version );
wp_enqueue_script( 'rank-math', rank_math()->assets() . 'js/rank-math.js', [ 'jquery' ], rank_math()->version, true );
}
wp_enqueue_style( 'rank-math-common', rank_math()->plugin_url() . 'assets/admin/css/common.css', null, rank_math()->version );
wp_enqueue_style( 'wp-components' );
wp_enqueue_style( 'rank-math-editor', rank_math()->plugin_url() . 'includes/3rdparty/divi/assets/css/divi.css', [], rank_math()->version );
wp_register_script( 'rank-math-analyzer', rank_math()->plugin_url() . 'assets/admin/js/analyzer.js', null, rank_math()->version, true );
wp_enqueue_script( 'rank-math-editor', rank_math()->plugin_url() . 'includes/3rdparty/divi/assets/js/divi.js', $divi_deps, rank_math()->version, true );
wp_enqueue_script( 'rank-math-divi-iframe', rank_math()->plugin_url() . 'includes/3rdparty/divi/assets/js/divi-iframe.js', [ 'jquery', 'lodash' ], rank_math()->version, true );
wp_set_script_translations( 'rank-math-app', 'seo-by-rank-math', rank_math()->plugin_dir() . 'languages/' );
wp_set_script_translations( 'rank-math-divi-iframe', 'seo-by-rank-math', rank_math()->plugin_dir() . 'languages/' );
wp_set_script_translations( 'rank-math-editor', 'seo-by-rank-math', rank_math()->plugin_dir() . 'languages/' );
wp_set_script_translations( 'rank-math-analyzer', 'seo-by-rank-math', rank_math()->plugin_dir() . 'languages/' );
if ( Helper::is_module_active( 'rich-snippet' ) ) {
wp_enqueue_style( 'rank-math-schema', rank_math()->plugin_url() . 'includes/modules/schema/assets/css/schema.css', [ 'wp-components' ], rank_math()->version );
wp_enqueue_script( 'rank-math-schema', rank_math()->plugin_url() . 'includes/modules/schema/assets/js/schema-gutenberg.js', [ 'rank-math-editor' ], rank_math()->version, true );
wp_set_script_translations( 'rank-math-schema', 'seo-by-rank-math', rank_math()->plugin_dir() . 'languages/' );
}
rank_math()->variables->setup();
rank_math()->variables->setup_json();
$this->screen->localize();
$this->print_react_containers();
/**
* Allow other plugins to enqueue/dequeue admin styles or scripts after plugin assets.
*/
$this->do_action( 'admin/editor_scripts', $this->screen );
}
/**
* Add et attributes to script tags.
*
* @param string $tag The <script> tag for the enqueued script.
* @param string $handle The script's registered handle.
*
* @return string
*/
public function add_et_tag( $tag, $handle ) {
$script_handles = [
'rm-react',
'rm-react-dom',
'lodash',
'moment',
'rank-math',
'rank-math-analyzer',
'rank-math-schema',
'rank-math-editor',
'rank-math-content-ai',
'rank-math-app',
// Scripts required by pro version.
'wp-plugins',
'jquery-ui-autocomplete',
'rank-math-pro-editor',
'rank-math-schema-pro',
'rank-math-pro-schema-filters',
'rank-math-pro-news',
];
$exclude_handles = [
'wp-util',
'wp-backbone',
'wp-plupload',
'wp-mediaelement',
'wp-color-picker',
'wp-color-picker-alpha',
'wp-embed',
'wp-hooks',
'wp-element',
];
if ( in_array( $handle, $exclude_handles, true ) ) {
return $tag;
}
if ( Str::starts_with( 'wp-', $handle ) || in_array( $handle, $script_handles, true ) ) {
// These tags load in parent window only, not in Divi iframe.
$tag = preg_replace(
'/<script\b(?![^>]*\bclass=)([^>]*)>/i',
'<script class="et_fb_ignore_iframe"$1>',
$tag
);
}
return $tag;
}
/**
* Print React containers onto the screen.
*/
public function print_react_containers() {
echo '<div id="rank-math-rm-app-root" class="et_fb_ignore_iframe"></div>';
echo '<div id="rank-math-rm-settings-bar-root" class="et_fb_ignore_iframe"></div>';
}
/**
* Can add SEO in Divi Page Builder.
*
* @return bool
*/
private function can_add_seo_tab() {
if (
! Helper::is_divi_frontend_editor() ||
! defined( 'ET_BUILDER_PRODUCT_VERSION' ) ||
! version_compare( '4.9.2', ET_BUILDER_PRODUCT_VERSION, 'le' )
) {
return false;
}
/**
* Filter to show/hide SEO Tab in Divi Editor.
*/
if ( ! $this->do_filter( 'divi/add_seo_tab', true ) ) {
return false;
}
$post_type = get_post_type();
if ( $post_type && ! Helper::get_settings( 'titles.pt_' . $post_type . '_add_meta_box' ) ) {
return false;
}
return Editor::can_add_editor();
}
/**
* Get Schema Data.
*
* @param int $post_id Post ID.
*
* @return array $schemas Schema Data.
*/
private function get_schema_data( $post_id ) {
$schemas = Schema_DB::get_schemas( $post_id );
if ( ! empty( $schemas ) || metadata_exists( 'post', $post_id, 'rank_math_rich_snippet' ) ) {
return $schemas;
}
$post_type = get_post_type( $post_id );
$default_type = ucfirst( Helper::get_default_schema_type( $post_id ) );
if ( ! $default_type ) {
return [];
}
$schemas['new-9999'] = [
'@type' => $default_type,
'metadata' => [
'title' => Helper::sanitize_schema_title( $default_type ),
'type' => 'template',
'shortcode' => uniqid( 's-' ),
'isPrimary' => true,
],
];
return $schemas;
}
/**
* Ensures required dependencies are loaded when toolbar is hidden.
*
* @return void
*/
private function maybe_load_editor_deps() {
if ( is_admin_bar_showing() ) {
return;
}
Helper::add_json( 'security', wp_create_nonce( 'rank-math-ajax-nonce' ) );
Helper::add_json( 'restNonce', ( wp_installing() && ! is_multisite() ) ? '' : wp_create_nonce( 'wp_rest' ) );
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,218 @@
<?php
/**
* Elementor integration.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Core
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Elementor;
use RankMath\Helper;
use RankMath\Traits\Hooker;
use RankMath\Helpers\Editor;
defined( 'ABSPATH' ) || exit;
/**
* Elementor class.
*/
class Elementor {
use Hooker;
/**
* Class constructor.
*/
public function __construct() {
$this->action( 'init', 'init' );
$this->filter( 'rank_math/frontend/robots', 'robots' );
$this->filter( 'rank_math/frontend/disable_integration', 'disable_frontend_integration' );
}
/**
* Initialize.
*/
public function init() {
if ( ! $this->can_add_seo_tab() ) {
return;
}
$this->action( 'elementor/editor/before_enqueue_scripts', 'enqueue' );
add_action( 'elementor/editor/footer', [ rank_math()->json, 'output' ], 0 );
$this->action( 'elementor/editor/footer', 'start_capturing', 0 );
$this->action( 'elementor/editor/footer', 'end_capturing', 999 );
$this->filter( 'rank_math/sitemap/content_before_parse_html_images', 'apply_builder_in_content', 10, 2 );
}
/**
* Disable frontend integration on Elementor Maintenance page.
*
* @since 1.0.91
*
* @param boolean $value Whether to run the frontend integration.
*/
public function disable_frontend_integration( $value ) {
$mode = get_option( 'elementor_maintenance_mode_mode' );
if ( ! in_array( $mode, [ 'maintenance', 'coming_soon' ], true ) ) {
return $value;
}
if ( ! get_option( 'elementor_maintenance_mode_template_id' ) ) {
return $value;
}
$exclude_mode = get_option( 'elementor_maintenance_mode_exclude_mode', [] );
if ( 'logged_in' === $exclude_mode && is_user_logged_in() ) {
return $value;
}
if ( 'custom' !== $exclude_mode ) {
return true;
}
$exclude_roles = get_option( 'elementor_maintenance_mode_exclude_roles', [] );
$user = wp_get_current_user();
$user_roles = $user->roles;
if ( is_multisite() && is_super_admin() ) {
$user_roles[] = 'super_admin';
}
$compare_roles = array_intersect( $user_roles, $exclude_roles );
return ! empty( $compare_roles ) ? $value : true;
}
/**
* Start capturing buffer.
*/
public function start_capturing() {
ob_start();
}
/**
* End capturing buffer and add button.
*/
public function end_capturing() {
$output = \ob_get_clean();
$search = '/(<(div|button) class="elementor-component-tab elementor-panel-navigation-tab" data-tab="global">.*<\/(div|button)>)/m';
$replace = '${1}<${2} class="elementor-component-tab elementor-panel-navigation-tab" data-tab="rank-math">SEO</${2}>';
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This comes from the output buffer, escaping it would break the output.
echo \preg_replace(
$search,
$replace,
$output
);
}
/**
* Enqueue scripts.
*/
public function enqueue() {
$deps = [
'wp-core-data',
'wp-components',
'wp-block-editor',
'wp-element',
'wp-data',
'wp-api-fetch',
'wp-media-utils',
'site-health',
'rank-math-analyzer',
'backbone-marionette',
'elementor-common-modules',
'rank-math-app',
];
if ( wp_script_is( 'elementor-v2-editor-app-bar', 'registered' ) ) {
$deps[] = 'elementor-v2-editor-app-bar';
}
$mode = \Elementor\Core\Settings\Manager::get_settings_managers( 'editorPreferences' )->get_model()->get_settings( 'ui_theme' );
wp_deregister_style( 'rank-math-editor' );
wp_enqueue_style( 'wp-components' );
wp_enqueue_style( 'site-health' );
wp_enqueue_style( 'rank-math-editor', rank_math()->plugin_url() . 'includes/3rdparty/elementor/assets/css/elementor.css', [ 'rank-math-common' ], rank_math()->version );
$media_query = '';
$dark_styles = $this->do_filter(
'elementor/dark_styles',
[
'rank-math-elementor-dark' => rank_math()->plugin_url() . 'includes/3rdparty/elementor/assets/css/elementor-dark.css',
]
);
if ( 'light' !== $mode ) {
$media_query = 'auto' === $mode ? '(prefers-color-scheme: dark)' : 'all';
foreach ( $dark_styles as $handle => $src ) {
wp_enqueue_style( $handle, $src, [], rank_math()->version, $media_query );
}
}
Helper::add_json( 'elementorDarkMode', $dark_styles );
wp_enqueue_script( 'rank-math-editor', rank_math()->plugin_url() . 'includes/3rdparty/elementor/assets/js/elementor.js', $deps, rank_math()->version, true );
rank_math()->variables->setup();
rank_math()->variables->setup_json();
}
/**
* Filters the post content before it is parsed for Sitmeap images..
* Used to apply the Elementor page editor on the post content.
*
* @since 1.0.38
*
* @param string $content The post content.
* @param int $post_id The post ID.
*
* @return string The post content.
*/
public function apply_builder_in_content( $content, $post_id ) {
if ( \Elementor\Plugin::$instance->db->is_built_with_elementor( $post_id ) ) {
return \Elementor\Plugin::$instance->frontend->get_builder_content( $post_id );
}
return $content;
}
/**
* Add SEO tab in Elementor Page Builder.
*
* @return bool
*/
private function can_add_seo_tab() {
/**
* Filter to show/hide SEO Tab in the Elementor Editor.
*/
if ( ! $this->do_filter( 'elementor/add_seo_tab', true ) ) {
return false;
}
$post_type = isset( $_GET['post'] ) ? get_post_type( absint( $_GET['post'] ) ) : '';
if ( $post_type && ! Helper::get_settings( 'titles.pt_' . $post_type . '_add_meta_box' ) ) {
return false;
}
return Editor::can_add_editor();
}
/**
* Change robots for Elementor Templates pages
*
* @param array $robots Array of robots to sanitize.
*
* @return array Modified robots.
*/
public function robots( $robots ) {
if ( is_singular( 'elementor_library' ) ) {
$robots['index'] = 'noindex';
$robots['follow'] = 'nofollow';
}
return $robots;
}
}
@@ -0,0 +1,141 @@
<?php
/**
* Loco Translate inline i18n helper for injecting translations without JSON files.
*
* @since 1.0.256
* @package RankMath
* @subpackage RankMath\Core
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\ThirdParty\Loco;
use RankMath\Traits\Hooker;
use RankMath\Helper;
use RankMath\Helpers\Str;
defined( 'ABSPATH' ) || exit;
/**
* Loco_I18n_Inline class.
*/
class Loco_I18n_Inline {
use Hooker;
/**
* Class constructor.
*/
public function __construct() {
$this->action( 'rank-math/admin_enqueue_scripts', 'inject_settings_locale' );
}
/**
* Inject inline JED locale for settings screens when Loco is active.
*/
public function inject_settings_locale() {
// Load translations from all Loco locations (Customization, System, Author).
$json = $this->get_jed_json( 'rank-math', false );
if ( empty( $json ) ) {
return;
}
$inline = sprintf(
'try{if(window.wp&&wp.i18n&&wp.i18n.setLocaleData){wp.i18n.setLocaleData(%s,"rank-math");var __rm=wp.i18n.getLocaleData&&wp.i18n.getLocaleData("rank-math");if(__rm){wp.i18n.setLocaleData(__rm,"seo-by-rank-math");}}}catch(e){}',
$json
);
wp_add_inline_script( 'common', $inline, 'before' );
}
/**
* Build a JED locale JSON from the best available MO/PO for the current locale.
*
* @param string $domain Text domain (e.g. 'rank-math').
* @param bool $loco_only Whether to restrict to Loco-managed files only.
* @return string JSON string suitable for wp.i18n.setLocaleData(), or empty string.
*/
private function get_jed_json( $domain, $loco_only = true ) {
$locale = get_user_locale();
$file = $this->find_translation_file( $domain, $locale, $loco_only );
if ( ! $file ) {
return '';
}
return $this->build_jed_json( $file, $domain, $locale );
}
/**
* Build JED JSON from translation file.
*
* @param string $file Path to MO or PO file.
* @param string $domain Text domain.
* @param string $locale Locale.
* @return string JSON string or false.
*/
private function build_jed_json( $file, $domain, $locale ) {
require_once ABSPATH . WPINC . '/pomo/mo.php';
require_once ABSPATH . WPINC . '/pomo/po.php';
$translations = Str::ends_with( '.mo', $file ) ? new \MO() : new \PO();
if ( ! $translations->import_from_file( $file ) ) {
return false;
}
$data = [
'' => [
'domain' => $domain,
'lang' => $locale,
],
];
if ( ! empty( $translations->headers['plural-forms'] ) ) {
$data['']['plural-forms'] = $translations->headers['plural-forms'];
}
foreach ( $translations->entries as $entry ) {
if ( empty( $entry->translations ) ) {
continue;
}
$key = empty( $entry->context ) ? $entry->singular : $entry->context . "\004" . $entry->singular;
$data[ $key ] = $entry->translations;
}
return wp_json_encode( $data );
}
/**
* Find translation file for domain/locale.
*
* @param string $domain Text domain.
* @param string $locale Locale.
* @param bool $loco_only Restrict to Loco files only.
* @return string|false File path or false.
*/
private function find_translation_file( $domain, $locale, $loco_only ) {
$paths = [];
// 1) Loco "Customization" location.
$paths[] = WP_CONTENT_DIR . '/languages/loco/plugins/' . $domain . '-' . $locale . '.mo';
$paths[] = WP_CONTENT_DIR . '/languages/loco/plugins/' . $domain . '-' . $locale . '.po';
// 2) Loco "System" location (global WP languages dir).
if ( ! $loco_only ) {
$paths[] = WP_LANG_DIR . '/plugins/' . $domain . '-' . $locale . '.mo';
$paths[] = WP_LANG_DIR . '/plugins/' . $domain . '-' . $locale . '.po';
}
// 3) Loco "Author" location (plugin bundled languages directory).
$paths[] = RANK_MATH_PATH . 'languages/' . $domain . '-' . $locale . '.mo';
$paths[] = RANK_MATH_PATH . 'languages/' . $domain . '-' . $locale . '.po';
foreach ( $paths as $path ) {
if ( is_file( $path ) && is_readable( $path ) ) {
return $path;
}
}
return false;
}
}
@@ -0,0 +1,546 @@
<?php
/**
* Polylang Integration.
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\ThirdParty
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\ThirdParty\Polylang;
use RankMath\Traits\Hooker;
use RankMath\Helpers\Str;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Polylang class.
*/
class Polylang {
use Hooker;
/**
* Class constructor.
*/
public function __construct() {
$this->action( 'pll_init', 'init' );
}
/**
* Initialize Polylang integration.
*/
public function init() {
// Reset Rank Math's settings cache so translated option values are used.
$this->action( 'wp_loaded', 'maybe_reset_settings_cache' );
// Register option keys with Polylang so get_option() returns per-language values.
$this->action( 'wp_loaded', 'register_option_translations' );
if ( \PLL() instanceof \PLL_Frontend ) {
$this->register_frontend_hooks();
return;
}
$this->register_admin_hooks();
}
/**
* Register hooks active only on the frontend.
*/
private function register_frontend_hooks() {
// Filter sitemap post queries by language to exclude inactive and foreign-domain posts.
$this->filter( 'rank_math/sitemap/post_count/join', 'sitemap_join_clause', 10, 2 );
$this->filter( 'rank_math/sitemap/post_count/where', 'sitemap_where_clause', 10, 2 );
$this->filter( 'rank_math/sitemap/get_posts/join', 'sitemap_join_clause', 10, 2 );
$this->filter( 'rank_math/sitemap/get_posts/where', 'sitemap_where_clause', 10, 2 );
$this->filter( 'pll_home_url_white_list', 'whitelist_home_url' );
$this->filter( 'rank_math/frontend/canonical', 'fix_home_canonical' );
$this->filter( 'rank_math/sitemap/xml_post_url', 'fix_front_page_sitemap_url', 10, 2 );
$this->filter( 'rank_math/opengraph/facebook', 'add_og_alternate_locales' );
if ( \PLL()->options['force_lang'] > 1 ) {
// Rewrite the home URL for multi-domain sitemaps; disable caching to prevent cross-domain URLs.
$this->filter( 'home_url', 'sitemap_home_url', 10, 2 );
$this->filter( 'rank_math/sitemap/enable_caching', 'enable_sitemap_caching' );
} else {
// Fix taxonomy sitemap queries and inject language-specific homepage/archive entries.
$this->filter( 'get_terms_args', 'update_term_query_args' );
$this->filter( 'rank_math/sitemap/exclude_post_type', 'inject_language_sitemap_entries', 0, 2 );
}
}
/**
* Register hooks active only in the admin.
*/
private function register_admin_hooks() {
$this->filter( 'pll_copy_post_metas', 'sync_post_metas', 10, 4 );
$this->filter( 'pll_translate_post_meta', 'translate_post_meta', 10, 3 );
$this->filter( 'pll_post_metas_to_export', 'export_post_metas' );
// Clear the sitemap cache when language settings change to prevent stale URLs.
$this->action( 'pll_add_language', 'clear_sitemap_cache' );
$this->action( 'pll_update_language', 'clear_sitemap_cache' );
$this->action( 'delete_term', 'clear_sitemap_cache_on_language_delete', 10, 3 );
}
/**
* Register Rank Math option keys with Polylang for per-language values.
*/
public function register_option_translations() {
$general_keys = [
'breadcrumbs_separator',
'breadcrumbs_prefix',
'breadcrumbs_home_label',
'breadcrumbs_archive_format',
'breadcrumbs_search_format',
'breadcrumbs_404_label',
'content_ai_country',
'content_ai_tone',
'content_ai_audience',
'content_ai_language',
'toc_block_title',
];
new \PLL_Translate_Option( 'rank-math-options-general', array_fill_keys( $general_keys, 1 ), [ 'context' => 'rank-math' ] );
$title_keys = [
'website_name',
'knowledgegraph_name',
'homepage_title',
'homepage_description',
'homepage_facebook_title',
'homepage_facebook_description',
'author_archive_title',
'author_archive_description',
'date_archive_title',
'date_archive_description',
'search_title',
'404_title',
];
foreach ( Helper::get_accessible_post_types() as $post_type ) {
$title_keys[] = "pt_{$post_type}_title";
$title_keys[] = "pt_{$post_type}_description";
$title_keys[] = "pt_{$post_type}_archive_title";
$title_keys[] = "pt_{$post_type}_archive_description";
$title_keys[] = "pt_{$post_type}_default_snippet_*";
}
new \PLL_Translate_Option( 'rank-math-options-titles', array_fill_keys( $title_keys, 1 ), [ 'context' => 'rank-math' ] );
}
/**
* Reset Rank Math's settings cache so translated option values are used.
*/
public function maybe_reset_settings_cache() {
if ( function_exists( 'pll_current_language' ) ) {
rank_math()->settings->reset();
}
}
/**
* The cache is keyed by post type only, so a sitemap cached for one domain
* would be served unchanged to every other domain, producing wrong URLs.
*
* @return false
*/
public function enable_sitemap_caching() {
return false;
}
/**
* Invalidate the entire Rank Math sitemap cache.
*/
public function clear_sitemap_cache() {
\RankMath\Sitemap\Cache_Watcher::clear();
}
/**
* `delete_term` fires for every taxonomy, so guard for `language` terms only.
*
* @param int $term_id Deleted term ID.
* @param int $tt_id Deleted term taxonomy ID.
* @param string $taxonomy Taxonomy the term belonged to.
*/
public function clear_sitemap_cache_on_language_delete( $term_id, $tt_id, $taxonomy ) {
if ( 'language' === $taxonomy ) {
$this->clear_sitemap_cache();
}
}
/**
* Rewrite home_url to the current-language domain when serving sitemaps.
*
* @param string $url URL being filtered.
* @param string $path URL path component.
* @return string
*/
public function sitemap_home_url( $url, $path ) {
$uri = empty( $path )
? ltrim( (string) wp_parse_url( pll_get_requested_url(), PHP_URL_PATH ), '/' )
: $path;
if ( 'sitemap_index.xml' === $uri || preg_match( '#([^/]+?)-sitemap([0-9]+)?\.xml|([a-z]+)?-?sitemap\.xsl#', $uri ) ) {
$url = \PLL()->links_model->switch_language_in_link( $url, \PLL()->curlang );
}
return $url;
}
/**
* Add a JOIN clause for Polylang's language table to sitemap post queries.
*
* @param string $sql Existing JOIN clause.
* @param string $post_type Post type being queried.
* @return string
*/
public function sitemap_join_clause( $sql, $post_type ) {
return pll_is_translated_post_type( $post_type )
? $sql . \PLL()->model->post->join_clause( 'p' )
: $sql;
}
/**
* Add a WHERE clause to include only active-language posts in sitemap queries.
*
* @param string $sql Existing WHERE clause.
* @param string $post_type Post type being queried.
* @return string
*/
public function sitemap_where_clause( $sql, $post_type ) {
if ( ! pll_is_translated_post_type( $post_type ) ) {
return $sql;
}
if ( \PLL()->options['force_lang'] > 1 && \PLL()->curlang instanceof \PLL_Language ) {
return $sql . \PLL()->model->post->where_clause( \PLL()->curlang );
}
$languages = $this->get_active_language_slugs();
if ( empty( $languages ) ) {
$languages = pll_languages_list();
}
return $sql . \PLL()->model->post->where_clause( $languages );
}
/**
* Include all active-language terms in taxonomy sitemap queries.
*
* @param array $args get_terms() arguments.
* @return array
*/
public function update_term_query_args( $args ) {
if ( isset( $GLOBALS['wp_query']->query['sitemap'] ) ) {
$args['lang'] = implode( ',', $this->get_active_language_slugs() );
}
return $args;
}
/**
* Hooked at priority 0, before exclusion decisions; $exclude always passes through unchanged.
*
* @param bool $exclude Whether this post type is excluded from the sitemap.
* @param string $post_type Post type slug.
* @return bool Unchanged $exclude value.
*/
public function inject_language_sitemap_entries( $exclude, $post_type ) {
if ( ! pll_is_translated_post_type( $post_type ) || ( 'post' === $post_type && get_option( 'page_on_front' ) ) ) {
return $exclude;
}
$this->filter( "rank_math/sitemap/{$post_type}_content", 'append_language_sitemap_entries' );
return $exclude;
}
/**
* Post type is parsed from the filter tag so one method can serve every post-type hook.
*
* @param string $content Existing sitemap XML for this post type.
* @return string
*/
public function append_language_sitemap_entries( $content ) {
preg_match( '#rank_math/sitemap/(.+)_content$#', current_filter(), $matches );
$post_type = $matches[1] ?? '';
if ( ! $post_type ) {
return $content;
}
$entries = 'post' === $post_type
? $this->home_language_sitemap_entries( $post_type )
: $this->archive_language_sitemap_entries( $post_type );
return $content . $entries;
}
/**
* Build sitemap <url> entries for the homepage in each active language.
*
* @param string $post_type Always 'post'.
* @return string
*/
private function home_language_sitemap_entries( $post_type ) {
$generator = new \RankMath\Sitemap\Generator();
$languages = wp_list_filter( \PLL()->model->get_languages_list(), [ 'active' => false ], 'NOT' );
$mod = \RankMath\Sitemap\Sitemap::get_last_modified_gmt( $post_type );
if ( ! empty( \PLL()->options['hide_default'] ) ) {
// The default-language homepage is already added by Rank Math.
$languages = wp_list_filter( $languages, [ 'slug' => pll_default_language() ], 'NOT' );
}
$output = '';
foreach ( $languages as $lang ) {
$output .= $generator->sitemap_url(
[
'loc' => \pll_home_url( $lang->slug ),
'mod' => $mod,
]
);
}
return $output;
}
/**
* Build sitemap <url> entries for a post-type archive in each active language.
*
* @param string $post_type Post type slug.
* @return string
*/
private function archive_language_sitemap_entries( $post_type ) {
$post_type_obj = get_post_type_object( $post_type );
if ( ! $post_type_obj->has_archive ) {
return '';
}
$slug = true === $post_type_obj->has_archive
? $post_type_obj->rewrite['slug']
: $post_type_obj->has_archive;
// Skip archive URLs that are backed by a WordPress page (e.g. WooCommerce shop).
$page_for_slug = function_exists( 'wpcom_vip_get_page_by_path' )
? wpcom_vip_get_page_by_path( $slug )
: get_page_by_path( $slug );
if ( $page_for_slug ) {
return '';
}
$generator = new \RankMath\Sitemap\Generator();
$languages = wp_list_filter( \PLL()->model->get_languages_list(), [ 'active' => false ], 'NOT' );
$mod = \RankMath\Sitemap\Sitemap::get_last_modified_gmt( $post_type );
// The archive for the current language is already added by Rank Math.
$languages = wp_list_filter( $languages, [ 'slug' => pll_current_language() ], 'NOT' );
$original_curlang = \PLL()->curlang;
$output = '';
foreach ( $languages as $lang ) {
\PLL()->curlang = $lang;
$output .= $generator->sitemap_url(
[
'loc' => \PLL()->links_model->switch_language_in_link( get_post_type_archive_link( $post_type ), $lang ),
'mod' => $mod,
]
);
}
\PLL()->curlang = $original_curlang;
return $output;
}
/**
* Allow Rank Math to modify home URLs, needed for sitemap URL rewriting.
*
* @param array $allowlist Existing Polylang home URL allowlist.
* @return array
*/
public function whitelist_home_url( $allowlist ) {
return array_merge( $allowlist, [ [ 'file' => 'seo-by-rank-math' ] ] );
}
/**
* Append the language path to the canonical URL for language homepages.
*
* @param string $canonical Canonical URL produced by Rank Math.
* @return string
*/
public function fix_home_canonical( $canonical ) {
global $post;
$post_id = (int) get_option( 'page_on_front' );
if ( ! is_home() && ( empty( $post ) || $post->ID !== pll_get_post( $post_id ) ) ) {
return $canonical;
}
$path = ltrim( (string) wp_parse_url( \pll_home_url( pll_current_language() ), PHP_URL_PATH ), '/' );
return $canonical . $path;
}
/**
* Point the front page's sitemap entry at its language home URL, not its slug.
*
* @param string $url URL being written to the sitemap.
* @param \WP_Post $post Post object.
* @return string
*/
public function fix_front_page_sitemap_url( $url, $post ) {
$page_on_front_id = (int) get_option( 'page_on_front' );
if ( ! $page_on_front_id ) {
return $url;
}
$lang = pll_get_post_language( $post->ID );
if ( ! $lang ) {
return $url;
}
if ( (int) $post->ID === (int) pll_get_post( $page_on_front_id, $lang ) ) {
return \PLL()->links_model->switch_language_in_link( trailingslashit( get_option( 'home' ) ), \PLL()->model->get_language( $lang ) );
}
return $url;
}
/**
* Output og:locale:alternate tags for each language that has a translation
* of the current page.
*/
public function add_og_alternate_locales() {
$og = new \RankMath\OpenGraph\OpenGraph();
$og->network = 'facebook';
foreach ( $this->get_og_alternate_languages() as $locale ) {
$og->tag( 'og:locale:alternate', $locale );
}
}
/**
* Add Rank Math meta keys to the list copied when a post is duplicated or synced.
*
* @param string[] $metas Meta keys that will be copied.
* @param bool $sync True when syncing translations, false when duplicating.
* @param int $from Source post ID.
* @param int $to Target post ID.
* @return string[]
*/
public function sync_post_metas( $metas, $sync, $from, $to ) {
if ( ! $sync ) {
$metas = array_merge( $metas, $this->translatable_meta_keys() );
$metas[] = 'rank_math_facebook_image';
$metas[] = 'rank_math_facebook_image_id';
$metas[] = 'rank_math_twitter_use_facebook';
$metas[] = 'rank_math_twitter_image';
$metas[] = 'rank_math_twitter_image_id';
$metas[] = 'rank_math_robots';
}
$sync_taxonomies = \PLL()->sync->taxonomies->get_taxonomies_to_copy( $sync, $from, $to );
foreach ( array_intersect(
get_taxonomies(
[
'hierarchical' => true,
'public' => true,
]
),
$sync_taxonomies
) as $taxonomy ) {
$metas[] = 'rank_math_primary_' . $taxonomy;
}
return $metas;
}
/**
* Translate the primary-term meta value when syncing a post to another language.
*
* @param int $value Term ID in the source language.
* @param string $key Meta key.
* @param string $lang Target language slug.
* @return int
*/
public function translate_post_meta( $value, $key, $lang ) {
if ( ! Str::starts_with( 'rank_math_primary_', $key ) ) {
return $value;
}
$taxonomy = str_replace( 'rank_math_primary_', '', $key );
if ( ! \PLL()->model->is_translated_taxonomy( $taxonomy ) ) {
return $value;
}
return pll_get_term( $value, $lang );
}
/**
* Include Rank Math's translatable meta keys in Polylang's export list.
*
* @param array $metas Existing export meta map (key => 1).
* @return array
*/
public function export_post_metas( $metas ) {
return array_merge( $metas, array_fill_keys( $this->translatable_meta_keys(), 1 ) );
}
/**
* Return active language slugs, or an empty array when all languages are active.
*
* @return string[]
*/
private function get_active_language_slugs() {
$languages = \PLL()->model->get_languages_list();
$inactive_languages = wp_list_filter( $languages, [ 'active' => false ] );
if ( $inactive_languages ) {
return wp_list_pluck( wp_list_filter( $languages, [ 'active' => false ], 'NOT' ), 'slug' );
}
return [];
}
/**
* Collect Facebook locale codes for every language with a translation of the current page.
*
* @return string[]
*/
private function get_og_alternate_languages() {
$alternates = [];
foreach ( \PLL()->model->get_languages_list() as $language ) {
if (
isset( \PLL()->curlang ) &&
\PLL()->curlang->slug !== $language->slug &&
\PLL()->links->get_translation_url( $language ) &&
isset( $language->facebook )
) {
$alternates[] = $language->facebook;
}
}
// Two languages can share the same Facebook locale; deduplicate.
return array_unique( $alternates );
}
/**
* Meta keys whose values are language-specific (title, description, etc.).
*
* @return string[]
*/
private function translatable_meta_keys() {
return [
'rank_math_title',
'rank_math_breadcrumb_title',
'rank_math_description',
'rank_math_facebook_title',
'rank_math_facebook_description',
'rank_math_twitter_title',
'rank_math_twitter_description',
'rank_math_focus_keyword',
];
}
}
@@ -0,0 +1,152 @@
<?php
/**
* WPML Integration.
*
* @since 1.0.256
* @package RankMath
* @subpackage RankMath\Core
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\ThirdParty;
use RankMath\Traits\Hooker;
defined( 'ABSPATH' ) || exit;
/**
* WPML class.
*/
class WPML {
use Hooker;
/**
* Class constructor.
*/
public function __construct() {
$this->action( 'save_post', 'save_post', 10, 3 );
$this->filter( 'rank_math/schema/update', 'update_schema', 10, 2 );
}
/**
* Update schema action handler.
*
* @param int $object_id Object ID.
* @param array $schemas Schemas.
*
* @return void
*/
public function update_schema( $object_id, $schemas ) {
$settings = get_option( 'icl_sitepress_settings', [] );
$custom_fields = $settings['translation-management']['custom_fields_translation'] ?? [];
foreach ( $schemas as $meta_id => $schema ) {
$type = is_array( $schema['@type'] ) ? $schema['@type'][0] : $schema['@type'];
$meta_key = 'rank_math_schema_' . $type;
if ( ! isset( $custom_fields[ $meta_key ] ) ) {
$custom_fields[ $meta_key ] = '2';
}
$settings['translation-management']['custom_fields_translation'] = $custom_fields;
}
update_option( 'icl_sitepress_settings', $settings );
}
/**
* Save post action handler.
*
* @param int $post_id Post ID.
* @param WP_Post $post Post object.
* @param bool $update Whether this is an existing post being updated or not.
*
* @return void
*/
public function save_post( $post_id, $post, $update ) {
if (
'revision' === $post->post_type ||
'publish' !== $post->post_status ||
! isset( $_POST['skip_sitepress_actions'] ) ||
! sanitize_text_field( wp_unslash( $_POST['skip_sitepress_actions'] ) ) ||
( isset( $_POST['post_ID'] ) && (int) $_POST['post_ID'] !== $post_id )
) {
return;
}
global $rm_wpml_translated_post_id;
if ( ! $update || ! $rm_wpml_translated_post_id ) {
$rm_wpml_translated_post_id = $post_id;
return;
}
$rm_wpml_translated_post_id = 0;
$content = $post->post_content;
$block_updated = $this->maybe_update_schema_blocks( $content, $post_id );
$shortcode_updated = $this->maybe_update_schema_shortcodes( $content );
if ( ! $block_updated && ! $shortcode_updated ) {
return;
}
wp_update_post(
[
'ID' => $post_id,
'post_content' => $content,
]
);
}
/**
* Maybe update schema blocks.
*
* @param string $content Post content.
* @param int $post_id Post ID.
*/
private function maybe_update_schema_blocks( &$content, $post_id ) {
preg_match_all( '/<!--\s*wp:rank-math\/rich-snippet\s*(\{.*\})\s*\/-->/m', $content, $blocks, PREG_SET_ORDER );
if ( empty( $blocks ) ) {
return false;
}
foreach ( $blocks as $block ) {
$attr = json_decode( $block[1], true );
$attr['post_id'] = $post_id;
$content = str_replace( $block[0], '<!-- wp:rank-math/rich-snippet ' . wp_json_encode( $attr, JSON_UNESCAPED_SLASHES ) . ' /-->', $content );
}
return true;
}
/**
* Maybe update schema shortcodes.
*
* @param string $content Post content.
*/
private function maybe_update_schema_shortcodes( &$content ) {
$pattern = '/\[rank_math_rich_snippet\s+([^\]]*)\]/';
if ( ! preg_match_all( $pattern, $content, $shortcodes, PREG_SET_ORDER ) ) {
return false;
}
$updated = false;
foreach ( $shortcodes as $shortcode ) {
$attributes = $shortcode[1];
// Remove id attribute with double quotes: id="...".
$new_attributes = preg_replace( '/id\s*=\s*"[^"]*"/', 'id=""', $attributes );
// Remove id attribute with single quotes: id='...'.
$new_attributes = preg_replace( "/id\s*=\s*'[^']*'/", "id=''", $new_attributes );
if ( $new_attributes !== $attributes ) {
$content = str_replace( $shortcode[0], '[rank_math_rich_snippet ' . $new_attributes . ']', $content );
$updated = true;
}
}
return $updated;
}
}
@@ -0,0 +1,263 @@
<?php
/**
* Ability: rank-math/create-ai-visibility-brand
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use WP_REST_Request;
use RankMath\Abilities\Ability_Interface;
use RankMath\AI_Visibility\Platforms;
use RankMath\AI_Visibility\Api\Brands_Controller;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/create-ai-visibility-brand ability.
*/
class Create_AI_Visibility_Brand implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Brands REST controller instance.
*
* @var Brands_Controller
*/
private $controller;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Brands_Controller|null $controller Controller instance.
*/
public function __construct( string $category, array $shared_meta, ?Brands_Controller $controller = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->controller = $controller ?? new Brands_Controller();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/create-ai-visibility-brand',
[
'category' => $this->category,
'label' => esc_html__( 'Create AI Visibility brand', 'seo-by-rank-math' ),
'description' => sprintf(
/* translators: %s: supported platform IDs. */
esc_html__(
'Creates a new brand for AI Visibility monitoring, triggering an initial analysis automatically. Ask which AI platforms to track. Supported platforms: %s. Selecting more than one requires the Expert plan; other plans may choose only one.',
'seo-by-rank-math'
),
Platforms::supported_as_string()
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'name', 'url', 'language', 'platforms' ],
'properties' => [
'name' => [
'type' => 'string',
'description' => esc_html__( 'Brand name.', 'seo-by-rank-math' ),
],
'url' => [
'type' => 'string',
'format' => 'uri',
'description' => esc_html__( 'Brand website URL.', 'seo-by-rank-math' ),
],
'description' => [
'type' => 'string',
'description' => esc_html__( 'Short description of the brand or product.', 'seo-by-rank-math' ),
'default' => '',
],
'locale' => [
'type' => 'string',
'description' => esc_html__( 'ISO 3166-1 alpha-2 country code (e.g. "US", "HU"). Defaults to no country filter.', 'seo-by-rank-math' ),
'default' => '',
],
'language' => [
'type' => 'string',
'description' => esc_html__( 'Language the brand should be analyzed in (e.g. "US English", "French"). Required; immutable after creation — ask the user which language to use.', 'seo-by-rank-math' ),
'enum' => Brands_Controller::get_language_choices( false ),
],
'interval' => [
'type' => 'string',
'description' => esc_html__( 'Analysis refresh cadence. Defaults to the account plan\'s default when omitted.', 'seo-by-rank-math' ),
'enum' => array_merge( [ '' ], Brands_Controller::get_interval_choices() ),
'default' => '',
],
'platforms' => [
'type' => 'array',
'minItems' => 1,
'description' => sprintf(
/* translators: %s: supported platform IDs. */
esc_html__( 'AI platforms to track. Supported: %s. Selecting more than one requires the Expert plan; otherwise choose exactly one. Do not assume a default — ask the user which platform(s) to use.', 'seo-by-rank-math' ),
Platforms::supported_as_string()
),
'items' => [
'type' => 'string',
'enum' => Platforms::supported(),
],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => false,
'destructive' => false,
'idempotent' => false,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$platforms = $this->validate_platforms( $input['platforms'] ?? null );
if ( isset( $platforms['error'] ) ) {
return $platforms;
}
$request = new WP_REST_Request( 'POST' );
$request->set_param( 'name', sanitize_text_field( (string) ( $input['name'] ?? '' ) ) );
$request->set_param( 'url', esc_url_raw( (string) ( $input['url'] ?? '' ) ) );
$request->set_param( 'description', sanitize_textarea_field( (string) ( $input['description'] ?? '' ) ) );
$request->set_param( 'locale', sanitize_text_field( (string) ( $input['locale'] ?? '' ) ) );
$request->set_param( 'language', sanitize_text_field( (string) ( $input['language'] ?? '' ) ) );
$request->set_param( 'interval', sanitize_text_field( (string) ( $input['interval'] ?? '' ) ) );
$request->set_param( 'platforms', $platforms );
$response = $this->controller->create_brand( $request );
if ( is_wp_error( $response ) ) {
return [ 'error' => $response->get_error_message() ];
}
$data = $response->get_data();
$brand = $data['data']['brand'] ?? [];
return [
'id' => $brand['id'] ?? '',
'name' => $brand['name'] ?? '',
'url' => $brand['url'] ?? '',
'interval' => $brand['interval'] ?? null,
'platforms' => $brand['platforms'] ?? [],
'analysis_status' => 'pending',
'created_at' => $brand['created_at'] ?? null,
];
}
/**
* Sanitize and validate platforms. No silent defaults.
*
* @param mixed $platforms Raw platforms value.
* @return string[]|array{error: string}
*/
private function validate_platforms( $platforms ) {
$valid = Platforms::validate( $platforms );
if ( is_wp_error( $valid ) ) {
return [ 'error' => $valid->get_error_message() ];
}
return Platforms::sanitize( $platforms );
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'string',
'description' => 'UUID of the newly created brand. Use this as brand_id in subsequent ability calls.',
],
'name' => [
'type' => 'string',
'description' => 'Brand name.',
],
'url' => [
'type' => 'string',
'format' => 'uri',
'description' => 'Brand website URL.',
],
'interval' => [
'type' => [ 'string', 'null' ],
'enum' => array_merge( [ null ], Brands_Controller::get_interval_choices() ),
'description' => 'Resolved analysis cadence for this brand.',
],
'platforms' => [
'type' => 'array',
'description' => 'AI platforms selected for this brand.',
'items' => [
'type' => 'string',
'enum' => Platforms::supported(),
],
],
'analysis_status' => [
'type' => 'string',
'enum' => [ 'pending' ],
'description' => 'Always "pending" on creation — the initial analysis is seeded automatically and will complete asynchronously.',
],
'created_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the brand was created.',
],
'error' => [
'type' => 'string',
'description' => 'Present only on failure — human-readable error from validation or the upstream API.',
],
],
];
}
}
@@ -0,0 +1,286 @@
<?php
/**
* Ability: rank-math/get-ai-visibility-brand-insights
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use RankMath\Abilities\Ability_Interface;
use RankMath\AI_Visibility\Cache;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-ai-visibility-brand-insights ability.
*/
class Get_AI_Visibility_Brand_Insights implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-ai-visibility-brand-insights',
[
'category' => $this->category,
'label' => esc_html__( 'Get AI Visibility brand insights', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the full analysis results for a single brand — AI Visibility score, rank, sentiment, mention and citation counts, per-competitor breakdown, and per-query results including the raw AI model responses.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'brand_id' ],
'properties' => [
'brand_id' => [
'type' => 'string',
'description' => esc_html__( 'Brand UUID. Obtain from get-ai-visibility-overview.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$brand_id = sanitize_text_field( (string) ( $input['brand_id'] ?? '' ) );
$cached = Cache::get_analysis( $brand_id );
if ( false === $cached || Cache::is_brand_stale( $brand_id ) ) {
rank_math()->tracking->track_ability_executed(
'AI Visibility Brand Insights Fetched',
[
'brand_id' => $brand_id,
'pending' => true,
'query_count' => 0,
'competitor_count' => 0,
],
'manage_options'
);
return [ 'pending' => true ];
}
$query_count = count( $cached['query_results'] ?? [] );
$competitor_count = count( $cached['competitors'] ?? [] );
rank_math()->tracking->track_ability_executed(
'AI Visibility Brand Insights Fetched',
[
'brand_id' => $brand_id,
'pending' => false,
'query_count' => $query_count,
'competitor_count' => $competitor_count,
],
'manage_options'
);
return array_merge( $cached, [ 'pending' => false ] );
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'pending' => [
'type' => 'boolean',
'description' => 'True when no completed analysis exists yet (e.g. brand was just added). All other fields are absent in this case.',
],
'score' => [
'type' => [ 'number', 'null' ],
'description' => 'AI Visibility score for this brand.',
],
'rank' => [
'type' => [ 'number', 'null' ],
'description' => 'Brand ranking position among competitors.',
],
'avg_sentiment' => [
'type' => [ 'number', 'null' ],
'description' => 'Average sentiment score across all mentions.',
],
'mentions' => [
'type' => [ 'number', 'null' ],
'description' => 'Total number of AI mentions.',
],
'citations' => [
'type' => [ 'number', 'null' ],
'description' => 'Total number of AI citations.',
],
'analyses' => [
'type' => 'array',
'description' => 'The latest completed analysis for each tracked AI platform (one entry per platform).',
'items' => [
'type' => 'object',
'properties' => [
'id' => [
'type' => [ 'string', 'null' ],
'description' => 'Analysis UUID.',
],
'platform' => [
'type' => [ 'string', 'null' ],
'description' => 'AI platform this analysis ran on (e.g. chatgpt, gemini).',
],
'status' => [
'type' => [ 'string', 'null' ],
'description' => 'Analysis status (e.g. done, processing, error).',
],
'started_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the analysis started.',
],
'finished_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the analysis completed.',
],
'duration_seconds' => [
'type' => [ 'number', 'null' ],
'description' => 'How long the analysis took in seconds.',
],
],
],
],
'competitors' => [
'type' => 'array',
'description' => 'Per-competitor breakdown for this brand.',
'items' => [
'type' => 'object',
'properties' => [
'name' => [
'type' => 'string',
'description' => 'Competitor brand name.',
],
'url' => [
'type' => [ 'string', 'null' ],
'format' => 'uri',
'description' => 'Competitor website URL.',
],
'mentions' => [
'type' => [ 'number', 'null' ],
'description' => 'Number of AI mentions for this competitor.',
],
'avg_sentiment' => [
'type' => [ 'number', 'null' ],
'description' => 'Average sentiment score for this competitor.',
],
],
],
],
'query_results' => [
'type' => 'array',
'description' => 'Per-query analysis results including raw AI model responses.',
'items' => [
'type' => 'object',
'properties' => [
'query_id' => [
'type' => [ 'string', 'null' ],
'description' => 'Query UUID.',
],
'query_text' => [
'type' => 'string',
'description' => 'The query that was submitted to the AI model.',
],
'platform' => [
'type' => [ 'string', 'null' ],
'description' => 'AI platform that produced this result (e.g. chatgpt, gemini).',
],
'found' => [
'type' => 'boolean',
'description' => 'Whether the brand was mentioned in the AI response.',
],
'rank' => [
'type' => [ 'number', 'null' ],
'description' => 'Brand rank among competitors for this query.',
],
'sentiment' => [
'type' => [ 'number', 'null' ],
'description' => 'Sentiment score for the brand mention in this query.',
],
'citations' => [
'type' => [ 'number', 'null' ],
'description' => 'Number of citations in the AI response for this query.',
],
'response' => [
'type' => 'string',
'description' => 'Raw text response returned by the AI model for this query.',
],
'extraction_data' => [
'type' => 'string',
'description' => 'Raw extraction data used to derive the structured results.',
],
],
],
],
],
];
}
}
@@ -0,0 +1,195 @@
<?php
/**
* Ability: rank-math/get-ai-visibility-brand-queries
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use RankMath\Abilities\Ability_Interface;
use RankMath\AI_Visibility\Cache;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-ai-visibility-brand-queries ability.
*/
class Get_AI_Visibility_Brand_Queries implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-ai-visibility-brand-queries',
[
'category' => $this->category,
'label' => esc_html__( 'Get AI Visibility brand queries', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the list of search queries being monitored for a brand, including which are currently enabled and which were auto-generated as baselines.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'brand_id' ],
'properties' => [
'brand_id' => [
'type' => 'string',
'description' => esc_html__( 'Brand UUID. Obtain from get-ai-visibility-overview or get-ai-visibility-brand-insights.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$brand_id = sanitize_text_field( (string) ( $input['brand_id'] ?? '' ) );
$cached = Cache::get_queries( $brand_id );
$queries = null !== $cached ? (array) ( $cached['queries'] ?? [] ) : [];
$total = count( $queries );
$enabled_count = count(
array_filter(
$queries,
function ( $q ) {
return ! empty( $q['enabled'] );
}
)
);
rank_math()->tracking->track_ability_executed(
'AI Visibility Brand Queries Fetched',
[
'brand_id' => $brand_id,
'total' => $total,
'enabled_count' => $enabled_count,
],
'manage_options'
);
return [
'brand_id' => $brand_id,
'queries' => $queries,
'total' => $total,
];
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'brand_id' => [
'type' => 'string',
'description' => 'The brand UUID the queries belong to.',
],
'queries' => [
'type' => 'array',
'description' => 'List of monitored queries for this brand.',
'items' => [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'string',
'description' => 'Query UUID.',
],
'text' => [
'type' => 'string',
'description' => 'The query text submitted to AI models.',
],
'enabled' => [
'type' => 'boolean',
'description' => 'Whether this query is currently active for analysis.',
],
'is_baseline' => [
'type' => 'boolean',
'description' => 'True when this query was auto-generated as a baseline by Rank Math.',
],
'created_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the query was created.',
],
'updated_at' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime when the query was last updated.',
],
],
],
],
'total' => [
'type' => 'integer',
'description' => 'Total number of queries returned.',
],
],
];
}
}
@@ -0,0 +1,233 @@
<?php
/**
* Ability: rank-math/get-ai-visibility-overview
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use RankMath\Abilities\Ability_Interface;
use RankMath\AI_Visibility\Cache;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-ai-visibility-overview ability.
*/
class Get_AI_Visibility_Overview implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-ai-visibility-overview',
[
'category' => $this->category,
'label' => esc_html__( 'Get AI Visibility overview', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the site-level AI Visibility summary and the full list of tracked brands with their current scores, ranks, sentiment, and analysis status.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'refresh' => [
'type' => 'boolean',
'description' => esc_html__( 'Pass true to bypass the 12-hour dashboard cache and return a stale-flagged response. Use the REST endpoint to trigger a fresh upstream fetch.', 'seo-by-rank-math' ),
'default' => false,
],
'search' => [
'type' => 'string',
'description' => esc_html__( 'Filter brands by name or URL (case-insensitive substring match).', 'seo-by-rank-math' ),
'default' => '',
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$refresh = (bool) ( $input['refresh'] ?? false );
$search = sanitize_text_field( (string) ( $input['search'] ?? '' ) );
$data = Cache::get_dashboard();
$summary = isset( $data['summary'] ) ? (array) $data['summary'] : [];
$brands = isset( $data['brands'] ) ? (array) $data['brands'] : [];
if ( '' !== $search ) {
$brands = array_values(
array_filter(
$brands,
function ( $row ) use ( $search ) {
return false !== stripos( $row['name'] ?? '', $search )
|| false !== stripos( $row['url'] ?? '', $search );
}
)
);
}
// Strip internal cache fields not relevant to MCP consumers.
$brands = array_map(
function ( $row ) {
unset( $row['stale'], $row['next_scheduled'], $row['created_at'] );
return $row;
},
$brands
);
rank_math()->tracking->track_ability_executed(
'AI Visibility Overview Fetched',
[
'brand_count' => count( $brands ),
'refresh' => $refresh,
],
'manage_options'
);
return [
'summary' => $summary,
'brands' => $brands,
];
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'summary' => [
'type' => 'object',
'description' => 'Site-level AI Visibility summary metrics.',
],
'brands' => [
'type' => 'array',
'description' => 'List of tracked brands with their current AI Visibility data.',
'items' => [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'string',
'description' => 'Brand UUID.',
],
'name' => [
'type' => 'string',
'description' => 'Brand name.',
],
'url' => [
'type' => 'string',
'format' => 'uri',
'description' => 'Brand website URL.',
],
'locale' => [
'type' => [ 'string', 'null' ],
'description' => 'ISO 3166-1 alpha-2 country code (e.g. "US").',
],
'status' => [
'type' => 'string',
'enum' => [ 'active', 'inactive' ],
'description' => 'Whether the brand is actively tracked.',
],
'score' => [
'type' => [ 'number', 'null' ],
'description' => 'AI Visibility score for this brand.',
],
'rank' => [
'type' => [ 'number', 'null' ],
'description' => 'Brand ranking position.',
],
'avg_sentiment' => [
'type' => [ 'number', 'null' ],
'description' => 'Average sentiment score across mentions.',
],
'mentions' => [
'type' => [ 'number', 'null' ],
'description' => 'Total number of AI mentions.',
],
'citations' => [
'type' => [ 'number', 'null' ],
'description' => 'Total number of AI citations.',
],
'analysis_status' => [
'type' => [ 'string', 'null' ],
'description' => 'Current analysis status (e.g. pending, processing, success, error).',
],
'last_analyzed' => [
'type' => [ 'string', 'null' ],
'format' => 'date-time',
'description' => 'ISO 8601 datetime of the last completed analysis.',
],
],
],
],
],
];
}
}
@@ -0,0 +1,109 @@
<?php
/**
* Subscriber for AI Visibility abilities.
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\AI_Visibility
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\AI_Visibility;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the AI Visibility ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for AI Visibility abilities.
*/
const CATEGORY_SLUG = 'rank-math-ai-visibility';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_ai_visibility_overview' );
$this->action( 'wp_abilities_api_init', 'register_get_ai_visibility_brand_insights' );
$this->action( 'wp_abilities_api_init', 'register_get_ai_visibility_brand_queries' );
$this->action( 'wp_abilities_api_init', 'register_create_ai_visibility_brand' );
}
/**
* Register the AI Visibility ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'AI Visibility', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to retrieve AI brand visibility data tracked by Rank Math.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-ai-visibility-overview ability.
*
* @return void
*/
public function register_get_ai_visibility_overview(): void {
( new Get_AI_Visibility_Overview( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/get-ai-visibility-brand-insights ability.
*
* @return void
*/
public function register_get_ai_visibility_brand_insights(): void {
( new Get_AI_Visibility_Brand_Insights( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/get-ai-visibility-brand-queries ability.
*
* @return void
*/
public function register_get_ai_visibility_brand_queries(): void {
( new Get_AI_Visibility_Brand_Queries( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/create-ai-visibility-brand ability.
*
* @return void
*/
public function register_create_ai_visibility_brand(): void {
( new Create_AI_Visibility_Brand( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,233 @@
<?php
/**
* Ability: rank-math/get-top-keywords
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Analytics
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Analytics;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-top-keywords ability.
*/
class Get_Top_Keywords implements Ability_Interface {
/**
* Maps date_range enum values to Stats::set_date_range() arguments.
*/
const DATE_RANGE_MAP = [
'last_7_days' => '-7 days',
'last_30_days' => '-30 days',
'last_3_months' => '-3 months',
'last_6_months' => '-6 months',
'last_12_months' => '-1 year',
];
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Runner instance.
*
* @var Top_Keywords_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Top_Keywords_Runner|null $runner Runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Top_Keywords_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Top_Keywords_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-top-keywords',
[
'category' => $this->category,
'label' => esc_html__( 'Get top keywords', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the top-performing keywords by clicks from Google Search Console, with impressions, CTR, and average position for the selected date range.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'date_range' => [
'type' => 'string',
'enum' => array_keys( self::DATE_RANGE_MAP ),
'default' => 'last_30_days',
'description' => esc_html__( 'Date range for which to fetch keyword data.', 'seo-by-rank-math' ),
],
'limit' => [
'type' => 'integer',
'default' => 25,
'minimum' => 1,
'maximum' => 100,
'description' => esc_html__( 'Maximum number of keywords to return.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_analytics' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$date_range = isset( $input['date_range'] ) && in_array( $input['date_range'], array_keys( self::DATE_RANGE_MAP ), true )
? (string) $input['date_range']
: 'last_30_days';
$limit = isset( $input['limit'] ) ? max( 1, min( 100, absint( $input['limit'] ) ) ) : 25;
$result = $this->runner->run( $date_range, $limit );
rank_math()->tracking->track_ability_executed(
'Top Keywords Fetched',
[
'limit' => $limit,
'date_range' => $date_range,
],
'rank_math_analytics'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'keywords' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'keyword' => [
'type' => 'string',
'description' => esc_html__( 'The search query keyword.', 'seo-by-rank-math' ),
],
'clicks' => [
'type' => 'integer',
'description' => esc_html__( 'Total clicks from Google Search Console.', 'seo-by-rank-math' ),
],
'impressions' => [
'type' => 'integer',
'description' => esc_html__( 'Total impressions from Google Search Console.', 'seo-by-rank-math' ),
],
'ctr' => [
'type' => 'number',
'description' => esc_html__( 'Click-through rate as a percentage (0–100).', 'seo-by-rank-math' ),
],
'position' => [
'type' => 'number',
'description' => esc_html__( 'Average position in Google Search results.', 'seo-by-rank-math' ),
],
'trend' => [
'type' => 'string',
'enum' => [ 'winning', 'losing', 'stable' ],
'description' => esc_html__( 'Position trend vs. the previous period. Provided by Rank Math PRO for tracked keywords.', 'seo-by-rank-math' ),
],
'is_tracked' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether this keyword is tracked in Rank Math PRO Rank Tracker.', 'seo-by-rank-math' ),
],
'ranking_posts' => [
'type' => 'array',
'description' => esc_html__( 'Pages on your site that rank for this keyword. Provided by Rank Math PRO.', 'seo-by-rank-math' ),
'items' => [
'type' => 'object',
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'WordPress post ID.', 'seo-by-rank-math' ),
],
'title' => [
'type' => 'string',
'description' => esc_html__( 'Post title.', 'seo-by-rank-math' ),
],
'slug' => [
'type' => 'string',
'description' => esc_html__( 'Relative URL path of the page.', 'seo-by-rank-math' ),
],
],
],
],
],
],
],
'date_range' => [
'type' => 'string',
'enum' => array_keys( self::DATE_RANGE_MAP ),
],
'connected' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether Google Search Console is connected.', 'seo-by-rank-math' ),
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Analytics abilities.
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Analytics
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Analytics;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Analytics ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Analytics abilities.
*/
const CATEGORY_SLUG = 'rank-math-analytics';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_top_keywords' );
}
/**
* Register the Analytics ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Analytics', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to query Google Search Console and analytics data.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-top-keywords ability.
*
* @return void
*/
public function register_get_top_keywords(): void {
( new Get_Top_Keywords( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1,101 @@
<?php
/**
* Top-keywords runner for the rank-math/get-top-keywords ability.
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Analytics
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Analytics;
use RankMath\Analytics\Stats;
use RankMath\Google\Console;
defined( 'ABSPATH' ) || exit;
/**
* Fetches top-performing keywords from Google Search Console and shapes the
* result for ability/MCP consumers.
*/
class Top_Keywords_Runner {
/**
* Stats service instance.
*
* @var Stats
*/
private $stats;
/**
* Constructor.
*
* @param Stats|null $stats Stats instance; defaults to the singleton.
*/
public function __construct( ?Stats $stats = null ) {
$this->stats = $stats ?? Stats::get();
}
/**
* Fetch and return the top keywords for the given date range.
*
* The keywords array is passed through the rank_math/analytics/ability/top_keywords
* filter so that the PRO plugin can annotate entries with position-trend data.
*
* @param string $date_range One of the Get_Top_Keywords::DATE_RANGE_MAP keys.
* @param int $limit Maximum number of keywords to return.
* @return array {
* @type array $keywords Flat list of keyword objects.
* @type string $date_range The date_range value that was used.
* @type bool $connected Whether Google Search Console is connected.
* }
*/
public function run( string $date_range, int $limit ): array {
if ( ! Console::is_console_connected() ) {
return [
'keywords' => [],
'date_range' => $date_range,
'connected' => false,
];
}
$range = isset( Get_Top_Keywords::DATE_RANGE_MAP[ $date_range ] )
? Get_Top_Keywords::DATE_RANGE_MAP[ $date_range ]
: Get_Top_Keywords::DATE_RANGE_MAP['last_30_days'];
$this->stats->set_date_range( $range );
$rows = $this->stats->get_analytics_data(
[
'dimension' => 'query',
'orderBy' => 'clicks',
'order' => 'DESC',
'offset' => 0,
'perpage' => $limit,
'objects' => true,
'pageview' => false,
]
);
$keywords = [];
foreach ( $rows as $query => $row ) {
$keywords[] = [
'keyword' => (string) $query,
'clicks' => (int) $row['clicks']['total'],
'impressions' => (int) $row['impressions']['total'],
'ctr' => (float) $row['ctr']['total'],
'position' => (float) $row['position']['total'],
];
}
// PRO plugin hooks here to annotate keywords with position trend data.
$keywords = apply_filters( 'rank_math/analytics/ability/top_keywords', $keywords, $date_range );
return [
'keywords' => $keywords,
'date_range' => $date_range,
'connected' => true,
];
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,105 @@
<?php
/**
* WordPress Abilities API integration for Rank Math SEO.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities;
use RankMath\Abilities\SEO_Analysis\Subscriber as SEO_Analysis_Subscriber;
use RankMath\Abilities\Link_Genius\Subscriber as Link_Genius_Subscriber;
use RankMath\Abilities\Post_SEO\Subscriber as Post_SEO_Subscriber;
use RankMath\Abilities\Schema\Subscriber as Schema_Subscriber;
use RankMath\Abilities\Analytics\Subscriber as Analytics_Subscriber;
use RankMath\Abilities\AI_Visibility\Subscriber as AI_Visibility_Subscriber;
use RankMath\Abilities\Settings\Subscriber as Settings_Subscriber;
use RankMath\Abilities\Content_Analysis\Subscriber as Content_Analysis_Subscriber;
use RankMath\Abilities\Sitemap\Subscriber as Sitemap_Subscriber;
use RankMath\Abilities\Monitor_404\Subscriber as Monitor_404_Subscriber;
use RankMath\Abilities\Redirections\Subscriber as Redirections_Subscriber;
defined( 'ABSPATH' ) || exit;
/**
* Bootstraps Rank Math feature subscribers with the WordPress Abilities API.
*/
class Abilities {
/**
* Singleton instance.
*
* @var Abilities
*/
private static $instance;
/**
* Get singleton.
*
* @return Abilities
*/
public static function get() {
if ( is_null( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor — registers feature subscribers if the Abilities API is available.
*/
public function __construct() {
if ( ! function_exists( 'wp_register_ability' ) ) {
return;
}
$this->register_subscribers();
}
/**
* Instantiate and register all feature subscribers.
*
* @return void
*/
private function register_subscribers() {
$shared_meta = $this->shared_meta();
$subscribers = [
new SEO_Analysis_Subscriber( $shared_meta ),
new Link_Genius_Subscriber( $shared_meta ),
new Post_SEO_Subscriber( $shared_meta ),
new Schema_Subscriber( $shared_meta ),
new Analytics_Subscriber( $shared_meta ),
new AI_Visibility_Subscriber( $shared_meta ),
new Settings_Subscriber( $shared_meta ),
new Content_Analysis_Subscriber( $shared_meta ),
new Sitemap_Subscriber( $shared_meta ),
new Monitor_404_Subscriber( $shared_meta ),
new Redirections_Subscriber( $shared_meta ),
];
foreach ( $subscribers as $subscriber ) {
$subscriber->register();
}
}
/**
* Default meta args shared by every ability we register.
*
* @return array
*/
private function shared_meta() {
return [
'show_in_rest' => true,
'annotations' => [
'readonly' => false,
'destructive' => false,
'idempotent' => true,
],
'mcp' => [ 'public' => true ],
];
}
}
@@ -0,0 +1,266 @@
<?php
/**
* Ability: rank-math/analyze-post-content
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Content_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Content_Analysis;
use RankMath\Abilities\Ability_Interface;
use RankMath\Rest\Rest_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/analyze-post-content ability.
*/
class Analyze_Post_Content implements Ability_Interface {
/**
* KB article covering all 24 on-page SEO tests, used as the scoring rubric reference.
*/
const KB_LINK = 'https://rankmath.com/kb/score-100-in-tests/';
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Content analysis data gatherer.
*
* @var Content_Analysis_Data
*/
private $data;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Content_Analysis_Data|null $data Content analysis data gatherer (injectable for tests).
*/
public function __construct( string $category, array $shared_meta, ?Content_Analysis_Data $data = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->data = $data ?? new Content_Analysis_Data();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/analyze-post-content',
[
'category' => $this->category,
'label' => esc_html__( 'Analyze post content', 'seo-by-rank-math' ),
'description' => esc_html__(
'Gathers the raw content, metadata, and list of on-page SEO tests for a saved post so an AI agent can run Rank Math\'s full on-page analysis itself, since the scoring engine only runs client-side. Use tests_to_run and content together with kb_link (the scoring rubric for all 24 tests) to evaluate each test and produce a per-test score, status, and fix message.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'required' => [ 'post_id' ],
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'ID of the post to analyze.', 'seo-by-rank-math' ),
],
'keyword' => [
'type' => 'string',
'description' => esc_html__( 'Optional focus keyword to analyze against, overriding the post\'s saved focus keyword.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_onpage_analysis' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_id = absint( $input['post_id'] );
$post = get_post( $post_id );
if ( ! $post || ! in_array( get_post_status( $post_id ), [ 'publish', 'draft', 'private', 'pending' ], true ) ) {
return [
'error' => [
'code' => 'invalid_post',
'message' => esc_html__( 'No post found with the given ID, or the post status is not supported.', 'seo-by-rank-math' ),
],
];
}
if ( ! Rest_Helper::can_edit_post( $post ) ) {
return [
'error' => [
'code' => 'rest_cannot_edit',
'message' => esc_html__( 'Sorry, you are not allowed to edit this post.', 'seo-by-rank-math' ),
],
];
}
if ( post_password_required( $post ) ) {
return [
'error' => [
'code' => 'post_password_required',
'message' => esc_html__( 'This post is password protected.', 'seo-by-rank-math' ),
],
];
}
$keyword = isset( $input['keyword'] ) ? sanitize_text_field( $input['keyword'] ) : '';
$payload = $this->data->get( $post, $keyword );
$result = [
'post_id' => $post_id,
'keyword' => $payload['content']['focus_keyword'],
'tests_to_run' => $payload['tests_to_run'],
'content' => $payload['content'],
'kb_link' => self::KB_LINK,
'instructions' => esc_html__(
'Evaluate each test ID in tests_to_run against the fields in content, using kb_link as the scoring rubric for how each test is scored. Return a per-test breakdown with score, max_score, status (pass/fail), and a message with a specific fix. For the contentHasTOC test, when suggesting a fix or drafting content, tell the user to insert the Rank Math Table of Contents block (block name rank-math/toc-block, available in the block inserter as "Table of Contents") right after the intro, instead of a manual list of links — it auto-generates from the post headings.',
'seo-by-rank-math'
),
'error' => null,
];
rank_math()->tracking->track_ability_executed(
'Post Content Analyzed',
[
'post_id' => $post_id,
'tests_count' => count( $payload['tests_to_run'] ),
'has_keyword' => ! empty( $result['keyword'] ),
],
'rank_math_onpage_analysis'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'post_id' => [ 'type' => 'integer' ],
'keyword' => [
'type' => 'string',
'description' => 'Focus keyword used for analysis (input override, or the post\'s saved keyword).',
],
'tests_to_run' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
'description' => 'IDs of the on-page SEO tests registered for this post, to be evaluated by the caller.',
],
'content' => [
'type' => 'object',
'description' => 'Raw content and metadata needed to evaluate each test in tests_to_run.',
'properties' => [
'title' => [ 'type' => 'string' ],
'description' => [ 'type' => 'string' ],
'permalink' => [ 'type' => 'string' ],
'focus_keyword' => [ 'type' => 'string' ],
'body' => [ 'type' => 'string' ],
'word_count' => [ 'type' => 'integer' ],
'excerpt_10pct' => [
'type' => 'string',
'description' => 'First 10% of the content body, used by the keywordIn10Percent test.',
],
'headings' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'level' => [ 'type' => 'string' ],
'text' => [ 'type' => 'string' ],
],
],
],
'images' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'alt' => [ 'type' => 'string' ],
],
],
],
'links' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'url' => [ 'type' => 'string' ],
'external' => [ 'type' => 'boolean' ],
],
],
],
],
],
'kb_link' => [
'type' => 'string',
'description' => 'KB article covering all 24 on-page SEO tests and how each is scored.',
],
'instructions' => [
'type' => 'string',
'description' => 'Guidance for the calling agent on how to use tests_to_run, content, and kb_link to produce a per-test analysis.',
],
'error' => [
'type' => [ 'object', 'null' ],
'properties' => [
'code' => [ 'type' => 'string' ],
'message' => [ 'type' => 'string' ],
],
],
],
];
}
}
@@ -0,0 +1,199 @@
<?php
/**
* Gathers raw content facts for the rank-math/analyze-post-content ability.
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Content_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Content_Analysis;
use WP_Post;
use RankMath\Helper;
use RankMath\Helpers\Str;
use RankMath\Helpers\Url;
use RankMath\Traits\Hooker;
defined( 'ABSPATH' ) || exit;
/**
* Builds the raw content payload an AI agent needs to evaluate the on-page SEO tests itself.
*
* This class does NOT score or judge anything — the actual test logic (Analyzer/Paper/Researcher)
* only exists client-side in JS and has no PHP port. Instead, it assembles the same facts the JS
* engine reads off the `Paper` object, so the calling agent can run the per-test evaluation.
*/
class Content_Analysis_Data {
use Hooker;
/**
* Canonical on-page test IDs for a post, mirroring Post_Screen::get_analysis().
*
* @var array
*/
const DEFAULT_TESTS = [
'contentHasTOC' => true,
'contentHasShortParagraphs' => true,
'contentHasAssets' => true,
'keywordInTitle' => true,
'keywordInMetaDescription' => true,
'keywordInPermalink' => true,
'keywordIn10Percent' => true,
'keywordInContent' => true,
'keywordInSubheadings' => true,
'keywordInImageAlt' => true,
'keywordDensity' => true,
'keywordNotUsed' => true,
'lengthContent' => true,
'lengthPermalink' => true,
'linksHasInternal' => true,
'linksHasExternals' => true,
'linksNotAllExternals' => true,
'titleStartWithKeyword' => true,
'titleSentiment' => true,
'titleHasPowerWords' => true,
'titleHasNumber' => true,
'hasContentAI' => true,
];
/**
* Build the content analysis payload for a post.
*
* @param WP_Post $post Post to analyze.
* @param string $keyword Optional focus keyword override.
* @return array
*/
public function get( WP_Post $post, string $keyword = '' ): array {
$post_id = $post->ID;
$body = $this->get_plain_text( $post->post_content );
$first_tenth = (int) ceil( mb_strlen( $body ) * 0.1 );
$title = Helper::get_post_meta( 'title', $post_id );
$description = Helper::get_post_meta( 'description', $post_id );
return [
'tests_to_run' => array_keys( $this->get_tests( $post->post_type ) ),
'content' => [
'title' => ! empty( $title ) ? $title : get_the_title( $post_id ),
'description' => ! empty( $description ) ? $description : '',
'permalink' => str_replace( home_url(), '', (string) get_permalink( $post_id ) ),
'focus_keyword' => '' !== $keyword ? $keyword : $this->get_primary_keyword( $post_id ),
'body' => $body,
'word_count' => str_word_count( $body ),
'excerpt_10pct' => Str::substr( $body, 0, $first_tenth ),
'headings' => $this->get_headings( $post->post_content ),
'images' => $this->get_images( $post->post_content ),
'links' => $this->get_links( $post->post_content ),
],
];
}
/**
* Get the on-page test IDs registered for a post type.
*
* @param string $post_type Post type slug.
* @return array
*/
private function get_tests( string $post_type ): array {
return $this->do_filter( 'researches/tests', self::DEFAULT_TESTS, $post_type );
}
/**
* Strip a post's content down to plain text.
*
* @param string $content Raw post content (may contain blocks/shortcodes/HTML).
* @return string
*/
private function get_plain_text( string $content ): string {
$content = strip_shortcodes( $content );
$content = wp_strip_all_tags( $content );
return trim( preg_replace( '/\s+/', ' ', $content ) );
}
/**
* Extract heading text grouped by level (H1-H6).
*
* @param string $content Raw post content.
* @return array
*/
private function get_headings( string $content ): array {
$headings = [];
if ( ! preg_match_all( '/<h([1-6])[^>]*>(.*?)<\/h\1>/is', $content, $matches, PREG_SET_ORDER ) ) {
return $headings;
}
foreach ( $matches as $match ) {
$headings[] = [
'level' => 'h' . $match[1],
'text' => trim( wp_strip_all_tags( $match[2] ) ),
];
}
return $headings;
}
/**
* Extract image alt text from post content.
*
* @param string $content Raw post content.
* @return array
*/
private function get_images( string $content ): array {
$images = [];
if ( ! preg_match_all( '/<img[^>]+>/i', $content, $matches ) ) {
return $images;
}
foreach ( $matches[0] as $tag ) {
$alt = preg_match( '/alt=["\']([^"\']*)["\']/i', $tag, $alt_match ) ? $alt_match[1] : '';
$images[] = [ 'alt' => $alt ];
}
return $images;
}
/**
* Extract links from post content, classified as internal or external.
*
* @param string $content Raw post content.
* @return array
*/
private function get_links( string $content ): array {
$links = [];
if ( ! preg_match_all( '/<a\s[^>]*href=["\']([^"\']+)["\'][^>]*>/i', $content, $matches ) ) {
return $links;
}
foreach ( $matches[1] as $href ) {
if ( Str::starts_with( '#', $href ) ) {
continue;
}
$links[] = [
'url' => $href,
'external' => Url::is_external( $href ),
];
}
return $links;
}
/**
* Get the primary focus keyword for the post.
*
* @param int $post_id Post ID.
* @return string
*/
private function get_primary_keyword( int $post_id ): string {
$keywords = get_post_meta( $post_id, 'rank_math_focus_keyword', true );
if ( empty( $keywords ) ) {
return '';
}
$parts = explode( ',', $keywords );
return trim( $parts[0] );
}
}
@@ -0,0 +1,359 @@
<?php
/**
* Ability: rank-math/get-seo-scores
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Content_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Content_Analysis;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-seo-scores ability.
*/
class Get_SEO_Scores implements Ability_Interface {
/**
* Default number of posts to return.
*/
const DEFAULT_NUMBER_OF_POSTS = 10;
/**
* Maximum number of posts to return.
*/
const MAX_NUMBER_OF_POSTS = 100;
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-seo-scores',
[
'category' => $this->category,
'label' => esc_html__( 'Get SEO scores', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns SEO scores and grades for posts. Before running, ask the user which posts they want to review: posts needing improvement (bad score), posts with no focus keyword, unscored posts, or simply the most recently modified posts. Use this to surface which posts need SEO attention without needing to know post IDs in advance.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'number_of_posts' => [
'type' => 'integer',
'description' => esc_html__( 'Number of recently modified posts to retrieve. Defaults to 10, maximum 100.', 'seo-by-rank-math' ),
'minimum' => 1,
'maximum' => self::MAX_NUMBER_OF_POSTS,
'default' => self::DEFAULT_NUMBER_OF_POSTS,
],
'post_type' => [
'type' => 'string',
'description' => esc_html__( 'Post type to filter by (e.g. "post", "page"). Defaults to all public post types.', 'seo-by-rank-math' ),
],
'seo_filter' => [
'type' => 'string',
'description' => esc_html__( 'Ask the user which posts they want to review before running this ability. Available options: "bad" (score ≤ 50, needs improvement), "good" (score 51–80, ok), "great" (score > 80), "empty-fk" (no focus keyword set), "unscored" (never analyzed). If the user does not specify, omit this parameter to return the most recently modified posts.', 'seo-by-rank-math' ),
'enum' => [ 'bad', 'good', 'great', 'empty-fk', 'unscored' ],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_onpage_analysis' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$limit = min( self::MAX_NUMBER_OF_POSTS, max( 1, absint( $input['number_of_posts'] ?? self::DEFAULT_NUMBER_OF_POSTS ) ) );
$post_type = isset( $input['post_type'] ) ? sanitize_key( $input['post_type'] ) : '';
$seo_filter = isset( $input['seo_filter'] ) ? sanitize_key( $input['seo_filter'] ) : '';
$meta_query = $this->build_meta_query( $seo_filter );
$query_args = [
'post_status' => 'publish',
'posts_per_page' => $limit,
'orderby' => 'modified',
'order' => 'DESC',
'fields' => 'ids',
];
if ( ! empty( $meta_query ) ) {
$query_args['meta_query'] = $meta_query;
// Order by score ascending for score-based filters so worst offenders surface first.
if ( in_array( $seo_filter, [ 'bad', 'good', 'great' ], true ) ) {
$query_args['orderby'] = 'meta_value_num';
$query_args['meta_key'] = 'rank_math_seo_score';
$query_args['order'] = 'ASC';
}
}
if ( ! empty( $post_type ) ) {
$query_args['post_type'] = $post_type;
} else {
$post_types = get_post_types( [ 'public' => true ] );
unset( $post_types['attachment'] );
$query_args['post_type'] = array_values( $post_types );
}
$post_ids = get_posts( $query_args );
$results = [];
foreach ( $post_ids as $post_id ) {
$results[] = $this->build_score_result( $post_id );
}
rank_math()->tracking->track_ability_executed(
'SEO Scores Retrieved',
[
'count' => count( $results ),
'post_type' => ! empty( $post_type ) ? $post_type : 'all',
'seo_filter' => ! empty( $seo_filter ) ? $seo_filter : 'none',
],
'rank_math_onpage_analysis'
);
return $results;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'post_id' => [ 'type' => 'integer' ],
'title' => [ 'type' => 'string' ],
'keyword' => [
'type' => [ 'string', 'null' ],
'description' => 'Primary focus keyword, or null if not set.',
],
'score' => [
'type' => [ 'integer', 'null' ],
'minimum' => 0,
'maximum' => 100,
],
'grade' => [
'type' => 'string',
'enum' => [ 'good', 'ok', 'bad', 'na' ],
],
'label' => [
'type' => 'string',
'description' => 'Human-readable grade label.',
],
'last_updated' => [ 'type' => 'integer' ],
],
],
];
}
/**
* Build the meta query for a given SEO filter.
*
* Mirrors the filter conditions defined in Post_Filters::set_seo_filters().
*
* @param string $filter SEO filter slug.
* @return array
*/
private function build_meta_query( string $filter ): array {
$hash = [
'empty-fk' => [
'key' => 'rank_math_focus_keyword',
'compare' => 'NOT EXISTS',
],
'unscored' => [
'key' => 'rank_math_seo_score',
'compare' => 'NOT EXISTS',
],
'bad' => [
'key' => 'rank_math_seo_score',
'value' => 50,
'compare' => '<=',
'type' => 'numeric',
],
'good' => [
'key' => 'rank_math_seo_score',
'value' => [ 51, 80 ],
'compare' => 'BETWEEN',
'type' => 'numeric',
],
'great' => [
'key' => 'rank_math_seo_score',
'value' => 80,
'compare' => '>',
'type' => 'numeric',
],
];
if ( ! isset( $hash[ $filter ] ) ) {
return [];
}
$meta_query = [];
// Score-based filters exclude noindexed posts and require a focus keyword, matching Post_Filters behaviour.
if ( in_array( $filter, [ 'bad', 'good', 'great' ], true ) ) {
$meta_query['relation'] = 'AND';
$meta_query[] = [
'relation' => 'OR',
[
'key' => 'rank_math_robots',
'value' => 'noindex',
'compare' => 'NOT LIKE',
],
[
'key' => 'rank_math_robots',
'compare' => 'NOT EXISTS',
],
];
$meta_query[] = [
'key' => 'rank_math_focus_keyword',
'compare' => 'EXISTS',
];
$meta_query[] = [
'key' => 'rank_math_focus_keyword',
'value' => '',
'compare' => '!=',
];
}
$meta_query[] = $hash[ $filter ];
return $meta_query;
}
/**
* Build the score result array for a single post.
*
* @param int $post_id Post ID.
* @return array
*/
private function build_score_result( int $post_id ): array {
$raw_score = get_post_meta( $post_id, 'rank_math_seo_score', true );
$keyword = $this->get_primary_keyword( $post_id );
if ( '' === $raw_score || false === $raw_score ) {
return [
'post_id' => $post_id,
'title' => get_the_title( $post_id ),
'keyword' => ! empty( $keyword ) ? $keyword : null,
'score' => null,
'grade' => 'na',
'label' => esc_html__( 'Not available', 'seo-by-rank-math' ),
'last_updated' => (int) get_post_modified_time( 'U', true, $post_id ),
];
}
$score = absint( $raw_score );
$grade = $score >= 80 ? 'good' : ( $score >= 50 ? 'ok' : 'bad' );
$label = $this->grade_to_label( $grade );
return [
'post_id' => $post_id,
'title' => get_the_title( $post_id ),
'keyword' => ! empty( $keyword ) ? $keyword : null,
'score' => $score,
'grade' => $grade,
'label' => $label,
'last_updated' => (int) get_post_modified_time( 'U', true, $post_id ),
];
}
/**
* Convert a grade slug to a human-readable label.
*
* @param string $grade Grade slug.
* @return string
*/
private function grade_to_label( string $grade ): string {
$labels = [
'good' => esc_html__( 'Good', 'seo-by-rank-math' ),
'ok' => esc_html__( 'OK', 'seo-by-rank-math' ),
'bad' => esc_html__( 'Needs improvement', 'seo-by-rank-math' ),
];
return $labels[ $grade ] ?? esc_html__( 'Not available', 'seo-by-rank-math' );
}
/**
* Get the primary focus keyword for a post.
*
* @param int $post_id Post ID.
* @return string
*/
private function get_primary_keyword( int $post_id ): string {
$keywords = get_post_meta( $post_id, 'rank_math_focus_keyword', true );
if ( empty( $keywords ) ) {
return '';
}
$parts = explode( ',', $keywords );
return trim( $parts[0] );
}
}
@@ -0,0 +1,89 @@
<?php
/**
* Subscriber for Content Analysis abilities.
*
* @since 1.0.274
* @package RankMath
* @subpackage RankMath\Abilities\Content_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Content_Analysis;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Content Analysis ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Content Analysis abilities.
*/
const CATEGORY_SLUG = 'rank-math-content-analysis';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_seo_scores' );
$this->action( 'wp_abilities_api_init', 'register_analyze_post_content' );
}
/**
* Register the Content Analysis ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Content Analysis', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to retrieve on-page SEO analysis scores for posts.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-seo-scores ability.
*
* @return void
*/
public function register_get_seo_scores(): void {
( new Get_SEO_Scores( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/analyze-post-content ability.
*
* @return void
*/
public function register_analyze_post_content(): void {
( new Analyze_Post_Content( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1,2 @@
<?php
// Silence is golden.
@@ -0,0 +1,41 @@
<?php
/**
* Interface for Rank Math abilities.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities;
defined( 'ABSPATH' ) || exit;
/**
* Ability interface.
*/
interface Ability_Interface {
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void;
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool;
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array;
}
@@ -0,0 +1,26 @@
<?php
/**
* Interface for Rank Math ability subscribers.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities;
defined( 'ABSPATH' ) || exit;
/**
* Subscriber interface.
*/
interface Subscriber_Interface {
/**
* Register the subscriber's category and abilities with WordPress hooks.
*
* @return void
*/
public function register(): void;
}
@@ -0,0 +1,207 @@
<?php
/**
* Ability: rank-math/get-link-report
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-link-report ability.
*/
class Get_Link_Report implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Runner instance.
*
* @var Link_Report_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Link_Report_Runner|null $runner Runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Link_Report_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Link_Report_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-link-report',
[
'category' => $this->category,
'label' => \esc_html__( 'Get link report', 'seo-by-rank-math' ),
'description' => \esc_html__(
'Returns a site-wide link health report: total internal and external links, post counts with no internal or external links, and — on Rank Math PRO — broken links, redirects, nofollow counts, and HTTP status distribution from the Link Genius audit.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'include_posts' => [
'type' => 'boolean',
'default' => false,
'description' => 'Whether to include per-post link counts in the response.',
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return \current_user_can( 'rank_math_link_builder' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$result = $this->runner->run( $input );
rank_math()->tracking->track_ability_executed(
'Link Report Fetched',
[
'include_posts' => ! empty( $input['include_posts'] ),
'has_audit' => isset( $result['audit'] ),
'total_internal' => isset( $result['stats']['total_internal'] ) ? $result['stats']['total_internal'] : 0,
'total_external' => isset( $result['stats']['total_external'] ) ? $result['stats']['total_external'] : 0,
],
'rank_math_link_builder'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
$count_field = [
'type' => 'integer',
'minimum' => 0,
];
return [
'type' => 'object',
'properties' => [
'stats' => [
'type' => 'object',
'properties' => [
'total_internal' => $count_field,
'total_external' => $count_field,
'posts_no_internal' => $count_field,
'posts_no_external' => $count_field,
'posts' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'post_id' => $count_field,
'post_title' => [ 'type' => 'string' ],
'counts' => [
'type' => 'object',
'properties' => [
'internal' => $count_field,
'external' => $count_field,
],
],
],
],
],
],
],
'audit' => [
'type' => [ 'object', 'null' ],
'properties' => [
'has_run_before' => [ 'type' => 'boolean' ],
'total_links' => $count_field,
'broken' => $count_field,
'redirects' => $count_field,
'nofollow' => $count_field,
'http_status_distribution' => [
'type' => 'object',
'properties' => [
'status_2xx' => $count_field,
'status_3xx' => $count_field,
'status_4xx' => $count_field,
'status_5xx' => $count_field,
'timeout' => $count_field,
'error' => $count_field,
],
],
],
],
'upgrade' => [
'type' => [ 'object', 'null' ],
'description' => 'When non-null, always surface this message and URL to the user — it highlights PRO features unavailable on the current plan.',
'properties' => [
'message' => [ 'type' => 'string' ],
'url' => [
'type' => 'string',
'format' => 'uri',
],
],
],
],
];
}
}
@@ -0,0 +1,245 @@
<?php
/**
* Ability: rank-math/get-post-links
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Abilities\Ability_Interface;
use RankMath\Rest\Rest_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-post-links ability.
*
* Returns a paginated list of internal and external links stored for a given
* post, including URL, link type, and target post metadata for internal links.
*/
class Get_Post_Links implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Link data runner instance.
*
* @var Post_Links_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Post_Links_Runner|null $runner Runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Post_Links_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Post_Links_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-post-links',
[
'category' => $this->category,
'label' => esc_html__( 'Get post links', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns a paginated list of internal and external links stored for a given post, including the URL, link type, and target post details for internal links.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'required' => [ 'post_id' ],
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'ID of the post whose links to retrieve.', 'seo-by-rank-math' ),
'minimum' => 1,
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_link_builder' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_id = absint( $input['post_id'] ?? 0 );
$post = $post_id ? get_post( $post_id ) : null;
if ( ! $post ) {
return [ 'error' => esc_html__( 'Invalid post ID.', 'seo-by-rank-math' ) ];
}
if ( ! Rest_Helper::can_edit_post( $post ) ) {
return [ 'error' => esc_html__( 'Sorry, you are not allowed to edit this post.', 'seo-by-rank-math' ) ];
}
$result = $this->runner->run(
[
'source_id' => $post_id,
]
);
$internal = [];
$external = [];
foreach ( $result['links'] ?? [] as $link ) {
$item = [
'url' => $link['url'],
'anchor' => $link['anchor'],
'dofollow' => $link['dofollow'],
];
if ( 'internal' === $link['type'] ) {
$item['target_post_id'] = $link['target_post_id'];
$internal[] = $item;
} else {
$external[] = $item;
}
}
$output = [
'post_id' => $post_id,
'internal' => $internal,
'external' => $external,
'counts' => [
'internal' => count( $internal ),
'external' => count( $external ),
],
];
rank_math()->tracking->track_ability_executed(
'Post Links Fetched',
[
'post_id' => $post_id,
'internal' => count( $internal ),
'external' => count( $external ),
],
'rank_math_link_builder'
);
return $output;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
$link_item = [
'type' => 'object',
'properties' => [
'url' => [
'type' => 'string',
'description' => 'Full URL of the link.',
],
'anchor' => [
'type' => [ 'string', 'null' ],
'description' => 'Anchor text of the link. Null when anchor data is unavailable (FREE plugin).',
],
'dofollow' => [
'type' => [ 'boolean', 'null' ],
'description' => 'True when the link is dofollow. Null when rel data is unavailable.',
],
],
];
$internal_item = $link_item;
$internal_item['properties']['target_post_id'] = [
'type' => 'integer',
'description' => 'WordPress post ID of the link target.',
];
return [
'type' => 'object',
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => 'WordPress post ID of the source post.',
],
'internal' => [
'type' => 'array',
'description' => 'Internal links found in the post.',
'items' => $internal_item,
],
'external' => [
'type' => 'array',
'description' => 'External links found in the post.',
'items' => $link_item,
],
'counts' => [
'type' => 'object',
'description' => 'Count of links returned per type.',
'properties' => [
'internal' => [
'type' => 'integer',
'description' => 'Number of internal links returned.',
],
'external' => [
'type' => 'integer',
'description' => 'Number of external links returned.',
],
],
],
'error' => [
'type' => 'string',
],
],
];
}
}
@@ -0,0 +1,91 @@
<?php
/**
* Runner for the get-link-report ability.
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Links\Api\Controller;
defined( 'ABSPATH' ) || exit;
/**
* Calls the existing Links REST controller methods to build a link report.
*/
class Link_Report_Runner {
/**
* Links REST controller.
*
* @var Controller
*/
private $controller;
/**
* Constructor.
*
* @param Controller|null $controller Links REST controller.
*/
public function __construct( ?Controller $controller = null ) {
$this->controller = $controller ?? new Controller();
}
/**
* Build and return the link report.
*
* @param array $input Ability input (e.g. include_posts).
* @return array
*/
public function run( array $input = [] ): array {
$posts_response = $this->controller->get_posts_stats();
$links_response = $this->controller->get_links_stats();
$posts = (array) $posts_response->get_data();
$links = (array) $links_response->get_data();
$total_posts = (int) ( $posts['total_posts'] ?? 0 );
$result = [
'stats' => [
'total_internal' => (int) ( $links['internal'] ?? 0 ),
'total_external' => (int) ( $links['external'] ?? 0 ),
'posts_no_internal' => $total_posts - (int) ( $posts['posts_with_internal'] ?? 0 ),
'posts_no_external' => $total_posts - (int) ( $posts['posts_with_external'] ?? 0 ),
],
];
if ( ! empty( $input['include_posts'] ) ) {
$data = $this->controller->get_posts_data( [ 'per_page' => 100 ] );
$result['stats']['posts'] = array_map(
function ( $post ) {
$row = (array) $post;
return [
'post_id' => (int) ( $row['post_id'] ?? 0 ),
'post_title' => (string) ( $row['post_title'] ?? '' ),
'counts' => [
'internal' => (int) ( $row['internal_link_count'] ?? 0 ),
'external' => (int) ( $row['external_link_count'] ?? 0 ),
],
];
},
$data['posts']
);
}
$result = (array) apply_filters( 'rank_math/abilities/link_report_result', $result, $input );
if ( ! isset( $result['audit'] ) ) {
$result['upgrade'] = [
'message' => \esc_html__( 'Upgrade to Rank Math PRO to unlock broken link detection, redirect chain analysis, and HTTP status distribution from the AI Link Genius audit.', 'seo-by-rank-math' ),
'url' => 'https://rankmath.com/pricing/',
];
}
return $result;
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Runner: fetches per-post link data via the existing links REST endpoint.
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Links\Api\Controller;
defined( 'ABSPATH' ) || exit;
/**
* Delegates to the Links REST controller to retrieve individual link rows for a post.
*
* Calls Controller::get_links() directly instead of going through the REST stack
* so that the request stays in-process. PRO plugin overrides
* (rank_math/links/rest_links_response) still apply because they live inside
* the controller callback itself.
*/
class Post_Links_Runner {
/**
* Links REST controller.
*
* @var Controller
*/
private $controller;
/**
* Constructor.
*
* @param Controller|null $controller Links REST controller (injectable for tests).
*/
public function __construct( ?Controller $controller = null ) {
$this->controller = $controller ?? new Controller();
}
/**
* Fetch link rows for a post by calling the links controller directly.
*
* @param array $args {
* Query arguments.
*
* @type int $post_id Source post ID. Must be > 0.
* @type int $page 1-based page number.
* @type int $per_page Rows per page (max 100).
* @type string $is_internal Filter value: '1' = internal only, '0' = external only, '' = all.
* }
* @return array { links: array, total: int, pages: int }
*/
public function run( array $args ): array {
$data = $this->controller->get_links_data( $args );
$links = [];
foreach ( $data['links'] ?? [] as $link ) {
$links[] = [
'id' => (int) $link->id,
'url' => $link->url,
'type' => $link->type,
'anchor' => (string) ( $link->anchor_text ?? '' ),
'dofollow' => isset( $link->is_nofollow ) ? ! (bool) $link->is_nofollow : null,
'target_post_id' => (int) ( $link->target_post_id ?? 0 ),
'target_title' => $link->target_title ?? '',
'target_url' => $link->target_url ?? '',
];
}
return [
'links' => $links,
'total' => (int) ( $data['total'] ?? 0 ),
'pages' => (int) ( $data['pages'] ?? 0 ),
];
}
}
@@ -0,0 +1,89 @@
<?php
/**
* Subscriber for Link Genius abilities.
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\Abilities\Link_Genius
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Link_Genius;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Link Genius ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Link Genius abilities.
*/
const CATEGORY_SLUG = 'rank-math-link-genius';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_link_report' );
$this->action( 'wp_abilities_api_init', 'register_get_post_links' );
}
/**
* Register the Link Genius ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'AI Link Genius', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to retrieve and analyse internal and external link data for posts.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-link-report ability.
*
* @return void
*/
public function register_get_link_report(): void {
( new Get_Link_Report( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/get-post-links ability.
*
* @return void
*/
public function register_get_post_links(): void {
( new Get_Post_Links( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,219 @@
<?php
/**
* Ability: rank-math/get-404-logs
*
* @since 1.0.279
* @package RankMath
* @subpackage RankMath\Abilities\Monitor_404
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Monitor_404;
use RankMath\Abilities\Ability_Interface;
use RankMath\Monitor\DB;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-404-logs ability.
*/
class Get_404_Logs implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-404-logs',
[
'category' => $this->category,
'label' => esc_html__( 'Get 404 logs', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the 404 error monitor log entries, with hit counts and referer/user-agent data.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'per_page' => [
'type' => 'integer',
'description' => esc_html__( 'The number of log entries to return per page.', 'seo-by-rank-math' ),
'default' => 100,
'minimum' => 1,
'maximum' => 1000,
],
'page' => [
'type' => 'integer',
'description' => esc_html__( 'The page number to return.', 'seo-by-rank-math' ),
'default' => 1,
],
'orderby' => [
'type' => 'string',
'enum' => [ 'hits', 'accessed' ],
'default' => 'hits',
'description' => esc_html__( 'Field to order results by.', 'seo-by-rank-math' ),
],
'order' => [
'type' => 'string',
'enum' => [ 'asc', 'desc' ],
'default' => 'desc',
'description' => esc_html__( 'Sort direction.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_404_monitor' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$per_page = isset( $input['per_page'] ) ? absint( $input['per_page'] ) : 100;
$page = max( 1, isset( $input['page'] ) ? (int) $input['page'] : 1 );
$orderby = isset( $input['orderby'] ) ? sanitize_text_field( $input['orderby'] ) : 'hits';
$order = isset( $input['order'] ) && in_array( $input['order'], [ 'asc', 'desc' ], true ) ? $input['order'] : 'desc';
$order_map = [
'hits' => 'times_accessed',
'accessed' => 'accessed',
];
$logs = DB::get_logs(
[
'orderby' => $order_map[ $orderby ] ?? 'times_accessed',
'order' => strtoupper( $order ),
'limit' => $per_page,
'paged' => $page,
]
);
$items = array_map(
function ( $log ) {
return [
'id' => (int) $log['id'],
'uri' => $log['uri'],
'hits' => (int) $log['times_accessed'],
'referer' => $log['referer'],
'user_agent' => $log['user_agent'],
'accessed' => $log['accessed'],
];
},
$logs['logs']
);
$stats = DB::get_stats();
$result = [
'stats' => [
'total_urls' => (int) ( $stats->total ?? 0 ),
'total_hits' => (int) ( $stats->hits ?? 0 ),
],
'total' => (int) $logs['count'],
'items' => $items,
];
rank_math()->tracking->track_ability_executed(
'404 Logs Fetched',
[ 'count' => (int) $logs['count'] ],
'rank_math_404_monitor'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'stats' => [
'type' => 'object',
'description' => esc_html__( 'Log counts across the entire table, independent of pagination.', 'seo-by-rank-math' ),
'properties' => [
'total_urls' => [ 'type' => 'integer' ],
'total_hits' => [ 'type' => 'integer' ],
],
],
'total' => [
'type' => 'integer',
'description' => esc_html__( 'Number of log entries included in this response (the size of items).', 'seo-by-rank-math' ),
],
'items' => [
'type' => 'array',
'description' => esc_html__( 'The 404 log entries for the requested page.', 'seo-by-rank-math' ),
'items' => [
'type' => 'object',
'properties' => [
'id' => [ 'type' => 'integer' ],
'uri' => [ 'type' => 'string' ],
'hits' => [ 'type' => 'integer' ],
'referer' => [ 'type' => 'string' ],
'user_agent' => [ 'type' => 'string' ],
'accessed' => [ 'type' => 'string' ],
],
],
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for 404 Monitor abilities.
*
* @since 1.0.279
* @package RankMath
* @subpackage RankMath\Abilities\Monitor_404
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Monitor_404;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the 404 Monitor ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for 404 Monitor abilities.
*/
const CATEGORY_SLUG = 'rank-math-404-monitor';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_404_logs' );
}
/**
* Register the 404 Monitor ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( '404 Monitor', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to inspect the 404 error monitor log.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-404-logs ability.
*
* @return void
*/
public function register_get_404_logs(): void {
( new Get_404_Logs( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,178 @@
<?php
/**
* Ability: rank-math/get-post-seo-meta
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Post_SEO
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Post_SEO;
use RankMath\Abilities\Ability_Interface;
use RankMath\Paper\Singular;
use RankMath\Rest\Rest_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-post-seo-meta ability.
*/
class Get_Post_SEO_Meta implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-post-seo-meta',
[
'category' => $this->category,
'label' => esc_html__( 'Get post SEO metadata', 'seo-by-rank-math' ),
'description' => esc_html__( 'Returns the full SEO metadata for a post: title, description, focus keyword, robots settings, canonical URL, Open Graph and Twitter overrides, and the current SEO score.', 'seo-by-rank-math' ),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'post_id' ],
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'The ID of the post to retrieve SEO metadata for.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_onpage_general' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_id = absint( $input['post_id'] );
$post = get_post( $post_id );
if ( ! $post || ! in_array( get_post_status( $post ), [ 'publish', 'draft', 'private', 'pending', 'future' ], true ) ) {
return [ 'error' => esc_html__( 'No post found with the given ID, or the post status is not supported.', 'seo-by-rank-math' ) ];
}
if ( ! Rest_Helper::can_edit_post( $post ) ) {
return [ 'error' => esc_html__( 'Sorry, you are not allowed to edit this post.', 'seo-by-rank-math' ) ];
}
$result = ( new Singular() )->get_seo_meta( $post_id );
if ( empty( $result['error'] ) ) {
rank_math()->tracking->track_ability_executed(
'Post SEO Meta Fetched',
[ 'post_id' => $post_id ],
'rank_math_onpage_general'
);
}
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'post_id' => [
'type' => 'integer',
],
'title' => [
'type' => 'string',
],
'description' => [
'type' => 'string',
],
'focus_keyword' => [
'type' => 'string',
],
'robots' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
],
'canonical' => [
'type' => 'string',
],
'og_title' => [
'type' => 'string',
],
'og_description' => [
'type' => 'string',
],
'twitter_title' => [
'type' => 'string',
],
'twitter_description' => [
'type' => 'string',
],
'seo_score' => [
'type' => 'integer',
'minimum' => 0,
'maximum' => 100,
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Post SEO abilities.
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Post_SEO
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Post_SEO;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Post SEO ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Post SEO abilities.
*/
const CATEGORY_SLUG = 'rank-math-post-seo';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_post_seo_meta' );
}
/**
* Register the Post SEO ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Post SEO', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to read and manage per-post SEO metadata.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-post-seo-meta ability.
*
* @return void
*/
public function register_get_post_seo_meta(): void {
( new Get_Post_SEO_Meta( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,233 @@
<?php
/**
* Ability: rank-math/get-redirections
*
* @since 1.0.278
* @package RankMath
* @subpackage RankMath\Abilities\Redirections
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Redirections;
use RankMath\Abilities\Ability_Interface;
use RankMath\Helper;
use RankMath\Redirections\DB;
use RankMath\Admin\Database\Database;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-redirections ability.
*/
class Get_Redirections implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-redirections',
[
'category' => $this->category,
'label' => esc_html__( 'Get redirections', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the redirections for a site.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'status' => [
'type' => 'string',
'enum' => [ 'active', 'inactive', 'all' ],
'default' => 'all',
'description' => esc_html__( 'Filter redirections by status.', 'seo-by-rank-math' ),
],
'per_page' => [
'type' => 'integer',
'description' => esc_html__( 'The number of redirections to return per page.', 'seo-by-rank-math' ),
'default' => 100,
'minimum' => 1,
'maximum' => 1000,
],
'page' => [
'type' => 'integer',
'description' => esc_html__( 'The page number to return.', 'seo-by-rank-math' ),
'default' => 1,
],
'search' => [
'type' => 'string',
'description' => esc_html__( 'Search redirections by source or target URL.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return Helper::has_cap( 'redirections' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$search = isset( $input['search'] ) ? sanitize_text_field( $input['search'] ) : '';
$status = isset( $input['status'] ) ? sanitize_text_field( $input['status'] ) : 'all';
$per_page = isset( $input['per_page'] ) ? absint( $input['per_page'] ) : 100;
$page = isset( $input['page'] ) ? absint( $input['page'] ) : 1;
$redirections = DB::get_redirections(
[
'limit' => $per_page,
'paged' => $page,
'search' => $search,
'status' => $status,
]
);
$items = array_map(
function ( $item ) {
$item['sources'] = maybe_unserialize( $item['sources'] );
return $item;
},
$redirections['redirections']
);
$counts = DB::get_counts();
$result = [
'stats' => [
'total' => absint( $counts['all'] ),
'active' => absint( $counts['active'] ),
'inactive' => absint( $counts['inactive'] ),
'by_type' => DB::get_counts_by_type(),
],
'total' => count( $items ),
'page' => $page,
'per_page' => $per_page,
'items' => $items,
];
rank_math()->tracking->track_ability_executed(
'Redirections Fetched',
[
'count' => $redirections['count'],
'status_filter' => $status,
],
'rank_math_redirections'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'stats' => [
'type' => 'object',
'description' => esc_html__( 'Redirection counts across all statuses, independent of the status filter applied to items.', 'seo-by-rank-math' ),
'properties' => [
'total' => [ 'type' => 'integer' ],
'active' => [ 'type' => 'integer' ],
'inactive' => [ 'type' => 'integer' ],
'by_type' => [
'type' => 'object',
'description' => esc_html__( 'Non-trashed redirection counts grouped by HTTP redirect type (header code), e.g. { "301": 12, "302": 4 }.', 'seo-by-rank-math' ),
'additionalProperties' => [ 'type' => 'integer' ],
],
],
],
'total' => [
'type' => 'integer',
'description' => esc_html__( 'Number of redirections included in this response (the size of items).', 'seo-by-rank-math' ),
],
'page' => [
'type' => 'integer',
],
'per_page' => [
'type' => 'integer',
],
'items' => [
'type' => 'array',
'description' => esc_html__( 'The redirections for the requested page.', 'seo-by-rank-math' ),
'items' => [
'type' => 'object',
'properties' => [
'id' => [ 'type' => 'integer' ],
'sources' => [ 'type' => 'array' ],
'url_to' => [ 'type' => 'string' ],
'header_code' => [ 'type' => 'integer' ],
'hits' => [ 'type' => 'integer' ],
'status' => [
'type' => 'string',
'enum' => [ 'active', 'inactive', 'trashed' ],
],
'created' => [ 'type' => 'string' ],
'updated' => [ 'type' => 'string' ],
'last_accessed' => [ 'type' => 'string' ],
],
],
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Redirection abilities.
*
* @since 1.0.278
* @package RankMath
* @subpackage RankMath\Abilities\Redirections
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Redirections;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Redirection ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Redirection abilities.
*/
const CATEGORY_SLUG = 'rank-math-redirections';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_redirections' );
}
/**
* Register the Redirection ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Redirections', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to read and manage redirections for a site.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-redirections ability.
*
* @return void
*/
public function register_get_redirections(): void {
( new Get_Redirections( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,221 @@
<?php
/**
* Ability: rank-math/get-post-schema
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Schema
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Schema;
use RankMath\Abilities\Ability_Interface;
use RankMath\Helper;
use RankMath\Rest\Rest_Helper;
use RankMath\Schema\DB;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-post-schema ability.
*/
class Get_Post_Schema implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-post-schema',
[
'category' => $this->category,
'label' => esc_html__( 'Get post schema', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the schema markup attached to a post and the schema types available on this install. Use this after rank-math/get-post-seo-meta to check what schema is already set and what types are supported before making a recommendation. If the schema type you want to recommend is not in available_types.types and upgrade_message is present, show upgrade_message verbatim to the user and do not suggest adding the schema type directly.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'post_id' ],
'properties' => [
'post_id' => [
'type' => 'integer',
'description' => esc_html__( 'The ID of the post to retrieve schema markup for.', 'seo-by-rank-math' ),
],
'include_available_types' => [
'type' => 'boolean',
'description' => esc_html__( 'When true (default), includes the schema types available on this install. Always pass true when evaluating which schema to add.', 'seo-by-rank-math' ),
'default' => true,
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_onpage_snippet' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_id = absint( $input['post_id'] );
$include = (bool) ( $input['include_available_types'] ?? true );
$post = $post_id ? get_post( $post_id ) : null;
if ( ! $post ) {
return [ 'error' => esc_html__( 'Invalid post ID.', 'seo-by-rank-math' ) ];
}
if ( ! Rest_Helper::can_edit_post( $post ) ) {
return [ 'error' => esc_html__( 'Sorry, you are not allowed to edit this post.', 'seo-by-rank-math' ) ];
}
$schemas = DB::get_schemas( $post_id );
$types_raw = DB::get_schema_types( $post_id );
$schema_types = $types_raw
? array_values( array_filter( array_map( 'trim', explode( ',', $types_raw ) ) ) )
: [];
$result = [
'post_id' => $post_id,
'schema_types' => $schema_types,
'schemas' => array_values( $schemas ),
];
if ( $include ) {
$result['available_types'] = $this->build_available_types();
}
rank_math()->tracking->track_ability_executed(
'Post Schema Fetched',
[
'post_id' => $post_id,
'schema_count' => count( $schemas ),
'include_available_types' => $include,
],
'rank_math_onpage_snippet'
);
return $result;
}
/**
* Build the available_types catalog.
*
* `types` lists what is installable right now: FREE types always present, PRO named
* types added automatically when PRO is active via rank_math/settings/snippet/types filter.
* `upgrade_message` is only present when PRO is not active; it is a ready-made sentence
* the agent should surface verbatim when a needed schema type is not in `types`.
*
* @return array
*/
private function build_available_types(): array {
$available = [
'types' => array_keys( Helper::choices_rich_snippet_types() ),
];
if ( ! defined( 'RANK_MATH_PRO_VERSION' ) ) {
$available['upgrade_message'] = esc_html__(
'This schema type requires Rank Math PRO. Upgrade at rankmath.com/pro to unlock Movie, Dataset, Fact Check, and custom schema types.',
'seo-by-rank-math'
);
}
return $available;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'post_id' => [
'type' => 'integer',
],
'schema_types' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
],
'schemas' => [
'type' => 'array',
'items' => [ 'type' => 'object' ],
],
'available_types' => [
'type' => 'object',
'properties' => [
'types' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
'description' => 'Schema type keys available on this install. FREE types always present; PRO named types added when PRO is active.',
],
'upgrade_message' => [
'type' => 'string',
'description' => 'Only present when PRO is not active. Show this verbatim to the user when the recommended schema type is not in types.',
],
],
],
'error' => [
'type' => 'string',
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Schema abilities.
*
* @since 1.0.272
* @package RankMath
* @subpackage RankMath\Abilities\Schema
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Schema;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Schema ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Schema abilities.
*/
const CATEGORY_SLUG = 'rank-math-schema';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_post_schema' );
}
/**
* Register the Schema ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Schema', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to read and manage schema markup attached to posts.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-post-schema ability.
*
* @return void
*/
public function register_get_post_schema(): void {
( new Get_Post_Schema( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,120 @@
<?php
/**
* Audit result value object for the rank-math/audit-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
defined( 'ABSPATH' ) || exit;
/**
* Site SEO audit result, agent-consumable shape.
*/
class Audit_Result {
/**
* Analyzed URL.
*
* @var string
*/
public $url;
/**
* Score 0–100.
*
* @var int
*/
public $score;
/**
* Grade: good|average|bad.
*
* @var string
*/
public $grade;
/**
* Outcome counts: ok, fail, warning, info.
*
* @var array
*/
public $statuses;
/**
* Total tests counted.
*
* @var int
*/
public $total_tests;
/**
* Unix timestamp of last run, 0 if never.
*
* @var int
*/
public $last_run_at;
/**
* Remote API status: ok|unavailable|skipped.
*
* @var string
*/
public $remote_api_status;
/**
* Per-test findings.
*
* @var Finding[]
*/
public $findings;
/**
* Error details when the audit could not run, or null on success.
* Shape: { code: string, message: string }
*
* @var array|null
*/
public $error;
/**
* Constructor.
*
* @param array $args See properties.
*/
public function __construct( array $args ) {
foreach ( $args as $key => $value ) {
if ( property_exists( $this, $key ) ) {
$this->{$key} = $value;
}
}
}
/**
* Serialize to array.
*
* @return array
*/
public function to_array() {
return [
'url' => $this->url,
'score' => (int) $this->score,
'grade' => $this->grade,
'statuses' => (array) $this->statuses,
'total_tests' => (int) $this->total_tests,
'last_run_at' => (int) $this->last_run_at,
'remote_api_status' => $this->remote_api_status,
'findings' => array_map(
function ( Finding $f ) {
return $f->to_array();
},
(array) $this->findings
),
'error' => $this->error,
];
}
}
@@ -0,0 +1,226 @@
<?php
/**
* Audit runner service for the rank-math/audit-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\KB;
use RankMath\Helpers\Url;
use RankMath\SEO_Analysis\SEO_Analyzer;
defined( 'ABSPATH' ) || exit;
/**
* Runs the Rank Math site SEO audit and shapes the result for ability/MCP consumers.
*/
class Audit_Runner {
/**
* SEO Analyzer instance.
*
* @var SEO_Analyzer
*/
private $analyzer;
/**
* Constructor.
*
* @param SEO_Analyzer|null $analyzer SEO Analyzer instance.
*/
public function __construct( ?SEO_Analyzer $analyzer = null ) {
$this->analyzer = $analyzer ?? new SEO_Analyzer();
}
/**
* Run the audit and return a structured result.
*
* External URL auditing requires Rank Math PRO. FREE installs receive
* an Audit_Result with error.code 'pro_required' instead of findings.
*
* @param bool $refresh Re-run tests instead of returning cached results.
* @param string|null $url Optional URL to audit. Defaults to this site's home URL.
* @return Audit_Result
*/
public function run( $refresh = true, $url = null ) {
if ( ! empty( $url ) ) {
$clean = wp_http_validate_url( $url );
if ( false === $clean ) {
return $this->error_result(
'invalid_url',
__( 'The provided URL is not valid.', 'seo-by-rank-math' )
);
}
if ( Url::is_external( $clean ) && ! apply_filters( 'rank_math/analysis/is_allowed_url', false, $clean ) ) {
return $this->error_result(
'pro_required',
sprintf(
/* translators: %s: URL to the Rank Math PRO upgrade page */
__( 'Competitor URL analysis requires Rank Math PRO. Upgrade at %s', 'seo-by-rank-math' ),
KB::get( 'pro', 'Audit Site SEO Ability' )
)
);
}
}
// The tests file is normally loaded only in the admin context. Include it here
// so local tests are available when the ability is invoked via REST/MCP.
$tests_file = RANK_MATH_PATH . 'includes/modules/seo-analysis/seo-analysis-tests.php';
if ( file_exists( $tests_file ) ) {
include_once $tests_file;
}
if ( ! empty( $url ) ) {
$this->analyzer->analyse_url = esc_url_raw( $url );
$this->analyzer->analyse_subpage = true;
}
$this->analyzer->set_url();
if ( $refresh || ! $this->has_cached_results() ) {
$this->analyzer->run_tests( $refresh );
} else {
$this->analyzer->get_results_from_storage();
}
return $this->shape( $this->analyzer );
}
/**
* Build a minimal Audit_Result carrying only an error (no findings).
*
* @param string $code Machine-readable error code.
* @param string $message Human-readable message for the AI/user.
* @return Audit_Result
*/
private function error_result( $code, $message ) {
return new Audit_Result(
[
'url' => '',
'score' => 0,
'grade' => 'bad',
'statuses' => [
'ok' => 0,
'fail' => 0,
'warning' => 0,
'info' => 0,
],
'total_tests' => 0,
'last_run_at' => 0,
'remote_api_status' => 'skipped',
'findings' => [],
'error' => [
'code' => $code,
'message' => $message,
],
]
);
}
/**
* Whether a cached audit result exists.
*
* @return bool
*/
private function has_cached_results() {
return (bool) get_option( 'rank_math_seo_analysis_results' );
}
/**
* Build an Audit_Result from a populated SEO_Analyzer.
*
* @param SEO_Analyzer $analyzer Populated analyzer instance.
* @return Audit_Result
*/
private function shape( SEO_Analyzer $analyzer ) {
$findings = [];
$statuses = [
'ok' => 0,
'fail' => 0,
'warning' => 0,
'info' => 0,
];
$total = 0;
$score_sum = 0;
$score_pass = 0;
if ( is_array( $analyzer->results ) ) {
foreach ( $analyzer->results as $id => $result ) {
if ( ! is_object( $result ) || $result->is_hidden() || $result->is_excluded() ) {
continue;
}
$data = $result->get_result();
$status = $result->get_status();
$score = (int) $result->get_score();
$statuses[ $status ] = isset( $statuses[ $status ] ) ? $statuses[ $status ] + 1 : 1;
++$total;
$score_sum += $score;
if ( 'ok' === $status ) {
$score_pass += $score;
}
// Prefer the per-run `message` (contains actual counts/links) over the
// static `description` (generic text defined in the test registration).
$description = isset( $data['message'] ) ? $data['message'] : ( isset( $data['description'] ) ? $data['description'] : '' );
$fix_html = isset( $data['fix'] ) ? $data['fix'] : '';
$findings[] = new Finding(
[
'test_id' => $id,
'category' => $result->get_category(),
'status' => $status,
'score' => $score,
'title' => isset( $data['title'] ) ? $data['title'] : '',
'description' => wp_strip_all_tags( $description ),
'fix_text' => html_entity_decode( wp_strip_all_tags( $fix_html ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ),
'fix_html' => $fix_html,
'fix_hint' => Fix_Hint_Map::get( $id ),
'kb_link' => isset( $data['kb_link'] ) ? $data['kb_link'] : '',
'data' => isset( $data['data'] ) ? $data['data'] : null,
]
);
}
}
$percent = $score_sum > 0 ? (int) round( ( $score_pass / $score_sum ) * 100 ) : 0;
return new Audit_Result(
[
'url' => $analyzer->analyse_url,
'score' => $percent,
'grade' => $this->grade_for( $percent ),
'statuses' => $statuses,
'total_tests' => $total,
'last_run_at' => (int) get_option( 'rank_math_seo_analysis_date', 0 ),
'remote_api_status' => $analyzer->remote_api_succeeded() ? 'ok' : 'unavailable',
'findings' => $findings,
'error' => null,
]
);
}
/**
* Score → grade bucket.
*
* @param int $percent Score percentage 0–100.
* @return string good|average|bad
*/
private function grade_for( $percent ) {
if ( $percent < 50 ) {
return 'bad';
}
if ( $percent < 70 ) {
return 'average';
}
return 'good';
}
}
@@ -0,0 +1,208 @@
<?php
/**
* Ability: rank-math/audit-site-seo
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/audit-site-seo ability.
*/
class Audit_Site_SEO implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Audit runner instance.
*
* @var Audit_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Audit_Runner|null $runner Audit runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Audit_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Audit_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/audit-site-seo',
[
'category' => $this->category,
'label' => esc_html__( 'Audit site SEO', 'seo-by-rank-math' ),
'description' => esc_html__(
"Runs Rank Math's site-wide SEO audit and returns a structured score plus per-test findings with fix hints. Combines local checks with the remote rankmath.com API tests.",
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'refresh' => [
'type' => 'boolean',
'description' => esc_html__( 'Re-run the audit. Defaults to true (always fresh when called by an AI host).', 'seo-by-rank-math' ),
'default' => true,
],
'url' => [
'type' => 'string',
'format' => 'uri',
'description' => esc_html__( "Optional URL to audit. Defaults to this site's home URL. When provided, only remote API tests run (local checks are site-wide).", 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_site_analysis' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$refresh = isset( $input['refresh'] ) ? (bool) $input['refresh'] : true;
$url = isset( $input['url'] ) ? $input['url'] : null;
$result = $this->runner->run( $refresh, $url )->to_array();
rank_math()->tracking->track_ability_executed(
'SEO Audit Run',
[
'score' => isset( $result['score'] ) ? $result['score'] : 0,
'grade' => isset( $result['grade'] ) ? $result['grade'] : '',
'has_url' => ! empty( $url ),
'has_error' => ! empty( $result['error'] ),
],
'rank_math_site_analysis'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'url' => [ 'type' => 'string' ],
'score' => [
'type' => 'integer',
'minimum' => 0,
'maximum' => 100,
],
'grade' => [
'type' => 'string',
'enum' => [ 'good', 'average', 'bad' ],
],
'statuses' => [
'type' => 'object',
'properties' => [
'ok' => [ 'type' => 'integer' ],
'fail' => [ 'type' => 'integer' ],
'warning' => [ 'type' => 'integer' ],
'info' => [ 'type' => 'integer' ],
],
],
'total_tests' => [ 'type' => 'integer' ],
'last_run_at' => [ 'type' => 'integer' ],
'remote_api_status' => [
'type' => 'string',
'enum' => [ 'ok', 'unavailable', 'skipped' ],
],
'findings' => [
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'test_id' => [ 'type' => 'string' ],
'category' => [
'type' => 'string',
'enum' => [ 'priority', 'basic', 'advanced', 'performance', 'security' ],
],
'status' => [
'type' => 'string',
'enum' => [ 'ok', 'fail', 'warning', 'info' ],
],
'score' => [ 'type' => 'integer' ],
'title' => [ 'type' => 'string' ],
'description' => [ 'type' => 'string' ],
'fix_text' => [ 'type' => 'string' ],
'fix_html' => [ 'type' => 'string' ],
'fix_hint' => [ 'type' => [ 'object', 'null' ] ],
'kb_link' => [ 'type' => 'string' ],
'data' => [ 'type' => [ 'object', 'array', 'null' ] ],
],
],
],
'error' => [
'type' => [ 'object', 'null' ],
'properties' => [
'code' => [ 'type' => 'string' ],
'message' => [ 'type' => 'string' ],
],
],
],
];
}
}
@@ -0,0 +1,130 @@
<?php
/**
* Finding value object for the rank-math/audit-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
defined( 'ABSPATH' ) || exit;
/**
* One SEO-audit test result, agent-consumable shape.
*/
class Finding {
/**
* Test identifier.
*
* @var string
*/
public $test_id;
/**
* Test category: priority|basic|advanced|performance|security.
*
* @var string
*/
public $category;
/**
* Test outcome: ok|fail|warning|info.
*
* @var string
*/
public $status;
/**
* Score contribution for this test.
*
* @var int
*/
public $score;
/**
* Human-readable test title.
*
* @var string
*/
public $title;
/**
* Plain-text description of the current result (actual counts/state, not static guidance).
*
* @var string
*/
public $description;
/**
* Plain-text how-to-fix — HTML tags and entities stripped, ready for AI consumption.
*
* @var string
*/
public $fix_text;
/**
* Original how-to-fix HTML, preserved for admin-UI consumers.
*
* @var string
*/
public $fix_html;
/**
* Structured fix hint an agent can act on, or null if none mapped.
*
* @var array|null
*/
public $fix_hint;
/**
* Knowledge-base article URL.
*
* @var string
*/
public $kb_link;
/**
* Free-form per-test supplemental data.
*
* @var mixed
*/
public $data;
/**
* Constructor.
*
* @param array $args See properties.
*/
public function __construct( array $args ) {
foreach ( $args as $key => $value ) {
if ( property_exists( $this, $key ) ) {
$this->{$key} = $value;
}
}
}
/**
* Serialize to array.
*
* @return array
*/
public function to_array() {
return [
'test_id' => $this->test_id,
'category' => $this->category,
'status' => $this->status,
'score' => (int) $this->score,
'title' => $this->title,
'description' => $this->description,
'fix_text' => $this->fix_text,
'fix_html' => $this->fix_html,
'fix_hint' => $this->fix_hint,
'kb_link' => $this->kb_link,
'data' => $this->data,
];
}
}
@@ -0,0 +1,94 @@
<?php
/**
* Fix hint map for the rank-math/audit-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
defined( 'ABSPATH' ) || exit;
/**
* Maps SEO-audit test IDs to structured fix hints an agent can act on.
*
* Kind:
* - 'wp_admin' → user/agent should open this WP admin page
* - 'setting' → fix is a Rank Math setting (`rank-math-options-{section}`)
* - 'ability' → another Rank Math ability can fix it (only entries for shipped abilities)
* - 'manual' → content edit per post; no single setting flip will resolve it
*
* Tests not in this map return null for fix_hint; the agent falls back to the
* `fix_html` text. Entries are added here as new abilities ship.
*/
class Fix_Hint_Map {
/**
* Retrieves the fix hint for a given test ID.
*
* @param string $test_id The ID of the test for which to retrieve a fix hint.
* @return array|null The fix hint array or null if not found.
*/
public static function get( $test_id ) {
$map = [
// Single WP setting fix.
'site_description' => [
'kind' => 'wp_admin',
'target' => 'options-general.php',
],
'permalink_structure' => [
'kind' => 'wp_admin',
'target' => 'options-permalink.php',
],
'blog_public' => [
'kind' => 'wp_admin',
'target' => 'options-reading.php',
],
// Rank Math settings panels.
'sitemaps' => [
'kind' => 'setting',
'target' => 'rank-math-options-sitemap',
],
'noindex' => [
'kind' => 'setting',
'target' => 'rank-math-options-titles',
],
'opengraph' => [
'kind' => 'setting',
'target' => 'rank-math-options-titles',
],
'schema' => [
'kind' => 'setting',
'target' => 'rank-math-options-titles',
],
'robots_txt' => [
'kind' => 'setting',
'target' => 'rank-math-options-general',
],
// Per-post content edits — no single flip; agent must walk posts.
'h1_heading' => [
'kind' => 'manual',
'target' => 'edit_post_content',
],
'h2_headings' => [
'kind' => 'manual',
'target' => 'edit_post_content',
],
'keywords_meta' => [
'kind' => 'manual',
'target' => 'edit_post_keywords',
],
'title_length' => [
'kind' => 'manual',
'target' => 'edit_post_titles',
],
];
return isset( $map[ $test_id ] ) ? $map[ $test_id ] : null;
}
}
@@ -0,0 +1,430 @@
<?php
/**
* Fix runner service for the rank-math/fix-site-seo ability.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Applies automatic fixes for failing SEO analysis tests.
*/
class Fix_Runner {
/**
* Maximum posts to process in a single synchronous fix call.
*/
const POST_LIMIT = 100;
/**
* Apply the fix for a given test and return a result summary.
*
* @param string $test_id SEO analysis test identifier.
* @param array $input Raw ability input (may include 'value', 'post_limit').
* @return array { fixed: bool, summary: string, details: array }
*/
public function fix( $test_id, array $input = [] ) {
$handler = 'fix_' . $test_id;
if ( ! method_exists( $this, $handler ) ) {
return $this->cannot_fix(
sprintf(
/* translators: %s: test ID */
__( 'No automatic fix is available for test "%s". Use the fix_text guidance to resolve it manually.', 'seo-by-rank-math' ),
$test_id
)
);
}
return $this->{$handler}( $input );
}
/**
* Fix: make the site visible to search engines.
*
* @param array $input Unused.
* @return array
*/
protected function fix_blog_public( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
update_option( 'blog_public', 1 );
return $this->ok( __( 'Site visibility set to public. Search engines can now index your site.', 'seo-by-rank-math' ) );
}
/**
* Fix: set permalink structure to /%postname%/.
*
* @param array $input Unused.
* @return array
*/
protected function fix_permalink_structure( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
global $wp_rewrite;
if ( '/%postname%/' === get_option( 'permalink_structure' ) ) {
return $this->ok( __( 'Permalink structure is already set to /%postname%/.', 'seo-by-rank-math' ) );
}
update_option( 'permalink_structure', '/%postname%/' );
$wp_rewrite->set_permalink_structure( '/%postname%/' );
$wp_rewrite->flush_rules( true );
return $this->ok( __( 'Permalink structure set to /%postname%/ and rewrite rules flushed.', 'seo-by-rank-math' ) );
}
/**
* Fix: set the site tagline to a custom value.
*
* Requires `value` in input — refuses if missing or looks like the default.
*
* @param array $input Must contain 'value'.
* @return array
*/
protected function fix_site_description( array $input ) {
$value = isset( $input['value'] ) ? sanitize_text_field( $input['value'] ) : '';
if ( empty( $value ) ) {
return $this->cannot_fix(
__( 'A "value" input is required to set the site tagline. Provide a short, unique description of your site.', 'seo-by-rank-math' )
);
}
if ( 'just another wordpress site' === strtolower( $value ) ) { // phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText
return $this->cannot_fix(
__( 'The provided tagline is the default WordPress value. Please supply a unique tagline.', 'seo-by-rank-math' )
);
}
update_option( 'blogdescription', $value );
return $this->ok(
sprintf(
/* translators: %s: tagline value */
__( 'Site tagline updated to: "%s".', 'seo-by-rank-math' ),
$value
)
);
}
// -------------------------------------------------------------------------
// Rank Math module fixes
// -------------------------------------------------------------------------
/**
* Fix: enable the Rank Math sitemap module.
*
* @param array $input Unused.
* @return array
*/
protected function fix_sitemaps( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
Helper::update_modules( [ 'sitemap' => 'on' ] );
return $this->ok( __( 'Sitemap module enabled. Your XML sitemap is now active.', 'seo-by-rank-math' ) );
}
/**
* Fix: enable the Rank Math schema (rich snippet) module.
*
* @param array $input Unused.
* @return array
*/
protected function fix_schema( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
Helper::update_modules( [ 'rich-snippet' => 'on' ] );
return $this->ok( __( 'Schema / rich snippet module enabled.', 'seo-by-rank-math' ) );
}
// -------------------------------------------------------------------------
// Rank Math settings fixes
// -------------------------------------------------------------------------
/**
* Fix: ensure the global robots setting does not include noindex.
*
* @param array $input Unused.
* @return array
*/
protected function fix_noindex( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
$titles = (array) get_option( 'rank-math-options-titles', [] );
$robots = isset( $titles['robots_global'] ) ? (array) $titles['robots_global'] : [ 'index', 'follow' ];
$robots = array_diff( $robots, [ 'noindex' ] );
if ( ! in_array( 'index', $robots, true ) ) {
$robots[] = 'index';
}
$titles['robots_global'] = array_values( $robots );
update_option( 'rank-math-options-titles', $titles );
return $this->ok( __( 'Global robots setting updated to allow indexing. Run a fresh audit to confirm the remote API test passes.', 'seo-by-rank-math' ) );
}
/**
* Fix: OpenGraph is always enabled in Rank Math — explain to the AI.
*
* @param array $input Unused.
* @return array
*/
protected function fix_opengraph( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
return $this->cannot_fix(
__( 'OpenGraph output is always enabled in Rank Math. If this test is failing, the remote audit API may need a fallback Open Graph image. Set one at Rank Math → Titles & Meta → Global Meta → Open Graph Thumbnail.', 'seo-by-rank-math' )
);
}
/**
* Fix: write a safe default robots.txt content into Rank Math settings.
*
* @param array $input Unused.
* @return array
*/
protected function fix_robots_txt( array $input ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found
$general = (array) get_option( 'rank-math-options-general', [] );
if ( isset( $general['robots_txt_content'] ) && '' !== trim( $general['robots_txt_content'] ) ) {
return $this->ok( __( 'Robots.txt content is already configured in Rank Math settings.', 'seo-by-rank-math' ) );
}
$general['robots_txt_content'] = "User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php";
update_option( 'rank-math-options-general', $general );
return $this->ok( __( 'Default robots.txt content written to Rank Math settings.', 'seo-by-rank-math' ) );
}
// -------------------------------------------------------------------------
// Per-post bulk fixes
// -------------------------------------------------------------------------
/**
* Fix: set a focus keyword on every published post that is missing one.
*
* The keyword is derived from the first 3 significant words of the post title.
* Accepts optional 'post_limit' input (default: POST_LIMIT).
*
* @param array $input Optional: post_limit (int).
* @return array
*/
protected function fix_focus_keywords( array $input ) {
$limit = isset( $input['post_limit'] ) ? absint( $input['post_limit'] ) : self::POST_LIMIT;
$limit = max( 1, min( $limit, 500 ) );
$types = Helper::get_allowed_post_types();
if ( empty( $types ) ) {
return $this->cannot_fix( __( 'No indexable post types are configured in Rank Math.', 'seo-by-rank-math' ) );
}
$posts = get_posts(
[
'post_type' => $types,
'post_status' => 'publish',
'posts_per_page' => $limit,
'meta_query' => [ // phpcs:ignore WordPress.DB.SlowDBQuery
[
'key' => 'rank_math_focus_keyword',
'compare' => 'NOT EXISTS',
],
],
'fields' => 'ids',
]
);
if ( empty( $posts ) ) {
return $this->ok( __( 'All published posts already have a focus keyword set.', 'seo-by-rank-math' ) );
}
$updated = 0;
$truncated = count( $posts ) >= $limit;
foreach ( $posts as $post_id ) {
$title = get_the_title( $post_id );
$keyword = $this->keyword_from_title( $title );
if ( empty( $keyword ) ) {
continue;
}
update_post_meta( $post_id, 'rank_math_focus_keyword', $keyword );
++$updated;
}
$summary = sprintf(
/* translators: 1: count updated, 2: total found */
__( 'Set focus keywords on %1$d posts (derived from post titles).', 'seo-by-rank-math' ),
$updated
);
if ( $truncated ) {
$summary .= ' ' . sprintf(
/* translators: %d: post_limit */
__( 'Results were limited to %d posts — run again to continue.', 'seo-by-rank-math' ),
$limit
);
}
return $this->ok(
$summary,
[
'updated' => $updated,
'truncated' => $truncated,
]
);
}
/**
* Fix: update the focus keyword to match the existing post title for posts where it doesn't.
*
* Changing the focus keyword (not the title) is safe: it doesn't affect URLs or published content.
* Accepts optional 'post_limit' input (default: POST_LIMIT).
*
* @param array $input Optional: post_limit (int).
* @return array
*/
protected function fix_post_titles( array $input ) {
global $wpdb;
$limit = isset( $input['post_limit'] ) ? absint( $input['post_limit'] ) : self::POST_LIMIT;
$limit = max( 1, min( $limit, 500 ) );
$types = Helper::get_allowed_post_types();
if ( empty( $types ) ) {
return $this->cannot_fix( __( 'No indexable post types are configured in Rank Math.', 'seo-by-rank-math' ) );
}
$in_post_types = "'" . implode( "','", array_map( 'esc_sql', $types ) ) . "'";
// Reuse the same query as the test — posts with focus keyword set but keyword not in title.
$meta_query = new \WP_Meta_Query(
[
'relation' => 'AND',
[
'key' => 'rank_math_focus_keyword',
'compare' => 'EXISTS',
],
[
'relation' => 'OR',
[
'key' => 'rank_math_robots',
'value' => 'noindex',
'compare' => 'NOT LIKE',
],
[
'key' => 'rank_math_robots',
'compare' => 'NOT EXISTS',
],
],
]
);
$mq_sql = $meta_query->get_sql( 'post', $wpdb->posts, 'ID' );
// phpcs:disable WordPress.DB.DirectDatabaseQuery
$rows = $wpdb->get_results(
$wpdb->prepare(
// phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder
"SELECT {$wpdb->posts}.ID, {$wpdb->posts}.post_title
FROM {$wpdb->posts} {$mq_sql['join']}
WHERE 1=1 {$mq_sql['where']}
AND {$wpdb->posts}.post_type IN ({$in_post_types})
AND {$wpdb->posts}.post_status = 'publish'
AND REPLACE( {$wpdb->posts}.post_title, %s, %s ) NOT LIKE
CONCAT( %s, SUBSTRING_INDEX( {$wpdb->postmeta}.meta_value, %s, 1 ), %s )
GROUP BY {$wpdb->posts}.ID
LIMIT %d",
'&amp;',
'&',
'%',
',',
'%',
$limit
)
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery
if ( empty( $rows ) ) {
return $this->ok( __( 'All posts with focus keywords already include them in their titles.', 'seo-by-rank-math' ) );
}
$updated = 0;
$truncated = count( $rows ) >= $limit;
foreach ( $rows as $row ) {
$keyword = $this->keyword_from_title( $row->post_title );
if ( empty( $keyword ) ) {
continue;
}
update_post_meta( (int) $row->ID, 'rank_math_focus_keyword', $keyword );
++$updated;
}
$summary = sprintf(
/* translators: %d: count updated */
__( 'Updated focus keywords on %d posts to match their titles.', 'seo-by-rank-math' ),
$updated
);
if ( $truncated ) {
$summary .= ' ' . sprintf(
/* translators: %d: post_limit */
__( 'Results were limited to %d posts — run again to continue.', 'seo-by-rank-math' ),
$limit
);
}
return $this->ok(
$summary,
[
'updated' => $updated,
'truncated' => $truncated,
]
);
}
/**
* Derive a focus keyword from a post title.
*
* Returns the first 3 words, lower-cased, with punctuation stripped.
* Returns empty string if nothing usable remains.
*
* @param string $title Post title.
* @return string
*/
private function keyword_from_title( $title ) {
$words = preg_split( '/\s+/', strtolower( html_entity_decode( $title, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ) );
$words = array_values(
array_filter(
$words,
function ( $w ) {
return ! empty( preg_replace( '/[^a-z0-9]/i', '', $w ) );
}
)
);
return implode( ' ', array_slice( $words, 0, 3 ) );
}
/**
* Return a successful fix result.
*
* @param string $summary Human-readable summary.
* @param array $details Optional extra data.
* @return array
*/
private function ok( $summary, array $details = [] ) {
return [
'fixed' => true,
'summary' => $summary,
'details' => $details,
];
}
/**
* Return a result indicating the fix could not be applied.
*
* @param string $summary Reason why the fix could not be applied.
* @return array
*/
private function cannot_fix( $summary ) {
return [
'fixed' => false,
'summary' => $summary,
'details' => [],
];
}
}
@@ -0,0 +1,173 @@
<?php
/**
* Ability: rank-math/fix-site-seo
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/fix-site-seo ability.
*/
class Fix_Site_SEO implements Ability_Interface {
/**
* Fixable test IDs — kept in sync with Fix_Runner handler methods.
*/
const FIXABLE_TEST_IDS = [
'blog_public',
'permalink_structure',
'site_description',
'sitemaps',
'schema',
'noindex',
'opengraph',
'robots_txt',
'focus_keywords',
'post_titles',
];
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Fix runner instance.
*
* @var Fix_Runner
*/
private $runner;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param Fix_Runner|null $runner Fix runner instance.
*/
public function __construct( string $category, array $shared_meta, ?Fix_Runner $runner = null ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->runner = $runner ?? new Fix_Runner();
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/fix-site-seo',
[
'category' => $this->category,
'label' => esc_html__( 'Fix site SEO', 'seo-by-rank-math' ),
'description' => esc_html__(
'Applies an automatic fix for a single failing Rank Math SEO test. Pass the test_id from an audit-site-seo finding. Some fixes require additional input (e.g. value for site_description). Bulk fixes accept an optional post_limit.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'test_id' ],
'properties' => [
'test_id' => [
'type' => 'string',
'enum' => self::FIXABLE_TEST_IDS,
'description' => esc_html__( 'The SEO test identifier to fix (from audit-site-seo findings).', 'seo-by-rank-math' ),
],
'value' => [
'type' => 'string',
'description' => esc_html__( 'Required for site_description: the new tagline to set.', 'seo-by-rank-math' ),
],
'post_limit' => [
'type' => 'integer',
'minimum' => 1,
'maximum' => 500,
'description' => esc_html__( 'For bulk post fixes (focus_keywords, post_titles): max posts to update in one call. Default 100.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => false,
'destructive' => false,
'idempotent' => false,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_site_analysis' ) && current_user_can( 'manage_options' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$test_id = (string) $input['test_id'];
$result = $this->runner->fix( $test_id, (array) $input );
rank_math()->tracking->track_ability_executed(
'SEO Audit Test Fixed',
[
'test_id' => $test_id,
'fixed' => ! empty( $result['fixed'] ),
],
'rank_math_site_analysis'
);
return $result;
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'fixed' => [ 'type' => 'boolean' ],
'summary' => [ 'type' => 'string' ],
'details' => [ 'type' => 'object' ],
],
];
}
}
@@ -0,0 +1,89 @@
<?php
/**
* Subscriber for SEO Analysis abilities.
*
* @since 1.0.271
* @package RankMath
* @subpackage RankMath\Abilities\SEO_Analysis
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\SEO_Analysis;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the SEO Analysis ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for SEO Analysis abilities.
*/
const CATEGORY_SLUG = 'rank-math-seo-analysis';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_audit_site_seo' );
$this->action( 'wp_abilities_api_init', 'register_fix_site_seo' );
}
/**
* Register the SEO Analysis ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'SEO Analysis', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to audit and fix site-wide SEO issues.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/audit-site-seo ability.
*
* @return void
*/
public function register_audit_site_seo(): void {
( new Audit_Site_SEO( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
/**
* Register the rank-math/fix-site-seo ability.
*
* @return void
*/
public function register_fix_site_seo(): void {
( new Fix_Site_SEO( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,195 @@
<?php
/**
* Abstract base class for Settings abilities.
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
use RankMath\Abilities\Ability_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Shared infrastructure for all Settings abilities.
*
* Provides the constructor, check_permissions(), option-reader helpers,
* apply_toggle_fields(), save_and_reset(), build_meta(), and write_success_schema()
* so concrete classes only need to implement register() and execute().
*/
abstract class Abstract_Ability implements Ability_Interface {
/**
* Allowed robots meta directive values — shared across abilities.
*/
const ROBOTS_DIRECTIVES = [ 'index', 'noindex', 'nofollow', 'noarchive', 'noimageindex', 'nosnippet' ];
/**
* Ability category slug.
*
* @var string
*/
protected $category;
/**
* Shared meta args.
*
* @var array
*/
protected $shared_meta;
/**
* WordPress capability required to execute this ability.
*
* @var string
*/
private $required_capability;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
* @param string $required_capability WP capability checked in check_permissions().
*/
public function __construct( string $category, array $shared_meta, string $required_capability ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
$this->required_capability = $required_capability;
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( $this->required_capability );
}
/**
* Current raw general option.
*
* @return array
*/
protected function get_general_option(): array {
return (array) get_option( 'rank-math-options-general', [] );
}
/**
* Current raw titles option.
*
* @return array
*/
protected function get_titles_option(): array {
return (array) get_option( 'rank-math-options-titles', [] );
}
/**
* Currently active module slugs.
*
* @return array<int, string>
*/
protected function get_active_modules(): array {
return (array) get_option( 'rank_math_modules', [] );
}
/**
* Accessible post type slugs.
*
* @return array<int, string>
*/
protected function get_accessible_post_types(): array {
return array_keys( Helper::get_accessible_post_types() );
}
/**
* Apply boolean-to-on/off toggle fields from input onto an option array.
*
* @param array $option Target option array (modified in-place).
* @param array $input Ability input.
* @param string[] $fields Field names to apply.
* @return void
*/
protected function apply_toggle_fields( array &$option, array $input, array $fields ): void {
foreach ( $fields as $field ) {
if ( isset( $input[ $field ] ) ) {
$option[ $field ] = $input[ $field ] ? 'on' : 'off';
}
}
}
/**
* Persist settings and flush the in-memory cache.
*
* @param array|null $general Updated general section, or null to leave untouched.
* @param array|null $titles Updated titles section, or null to leave untouched.
* @param array|null $sitemap Updated sitemap section, or null to leave untouched.
* @return void
*/
protected function save_and_reset( ?array $general, ?array $titles, ?array $sitemap ): void {
Helper::update_all_settings( $general, $titles, $sitemap );
rank_math()->settings->reset();
}
/**
* Build the meta array for wp_register_ability(), merging in annotations.
*
* @param bool $read_only Whether this ability only reads data.
* @return array
*/
protected function build_meta( bool $read_only ): array {
return array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => $read_only,
'destructive' => false,
'idempotent' => true,
],
]
);
}
/**
* JSON schema fragment common to all write-ability success responses.
*
* @param bool $with_error Include the error property.
* @param string $updated_description Description for the updated field.
* @return array
*/
protected function write_success_schema( bool $with_error = false, string $updated_description = 'List of field names that were updated.' ): array {
$schema = [
'type' => 'object',
'properties' => [
'saved' => [
'type' => 'boolean',
'description' => 'Whether the update was saved.',
],
'updated' => [
'type' => 'array',
'items' => [ 'type' => 'string' ],
'description' => $updated_description,
],
],
];
if ( $with_error ) {
$schema['properties']['error'] = [
'type' => 'object',
'description' => 'Present only when the update failed validation.',
'properties' => [
'code' => [ 'type' => 'string' ],
'message' => [ 'type' => 'string' ],
],
];
}
return $schema;
}
}
@@ -0,0 +1,138 @@
<?php
/**
* Ability: rank-math/get-llms-txt
*
* @since 1.0.278
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
use RankMath\LLMS\LLMS_Txt;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-llms-txt ability.
*
* Delegates entirely to LLMS_Txt::output(), capturing its echoed Markdown
* output via an output buffer rather than reimplementing the generation logic.
*/
class Get_Llms_Txt extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_general' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-llms-txt',
[
'category' => $this->category,
'label' => esc_html__( 'Get llms.txt', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns whether the llms.txt file is enabled, its URL, and the current generated Markdown content.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( true ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$enabled = $this->is_enabled();
$result = [
'enabled' => $enabled,
'url' => home_url( '/llms.txt' ),
'content' => $enabled ? $this->fetch_content() : '',
];
rank_math()->tracking->track_ability_executed(
'LLMs Txt Fetched',
[ 'enabled' => $enabled ],
'rank_math_general'
);
return $result;
}
/**
* Whether the llms.txt module is active. Extracted for testability.
*
* @return bool
*/
protected function is_enabled(): bool {
return Helper::is_module_active( 'llms-txt' );
}
/**
* Capture the LLMS_Txt::output() Markdown content via an output buffer.
*
* Output() also sends a couple of headers (Content-Type: text/plain,
* X-Robots-Tag) as a side effect of reuse — harmless here since the
* REST/MCP response sends its own headers afterward. Extracted for
* testability.
*
* @return string
*/
protected function fetch_content(): string {
ob_start();
( new LLMS_Txt() )->output();
return (string) ob_get_clean();
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'enabled' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether the llms.txt module is active.', 'seo-by-rank-math' ),
],
'url' => [
'type' => 'string',
'description' => esc_html__( 'The URL of the llms.txt file.', 'seo-by-rank-math' ),
],
'content' => [
'type' => 'string',
'description' => esc_html__( 'The generated llms.txt Markdown content. Empty when the module is disabled.', 'seo-by-rank-math' ),
],
],
];
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Ability: rank-math/get-robots-txt
*
* @since 1.0.278
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Robots_Txt;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-robots-txt ability.
*/
class Get_Robots_Txt extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_general' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-robots-txt',
[
'category' => $this->category,
'label' => esc_html__( 'Get robots.txt', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the current robots.txt content managed by Rank Math.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
],
'output_schema' => [
'type' => 'object',
'properties' => [
'content' => [
'type' => 'string',
'description' => esc_html__( 'The current robots.txt content: the real file contents when a physical robots.txt exists, otherwise the content Rank Math generates (custom override or computed default).', 'seo-by-rank-math' ),
],
'exists' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether a physical robots.txt file exists in the site root.', 'seo-by-rank-math' ),
],
'public' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether the site is set to be visible to search engines (Settings > Reading > Search engine visibility).', 'seo-by-rank-math' ),
],
],
],
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( true ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$data = $this->get_robots_data();
rank_math()->tracking->track_ability_executed(
'Robots Txt Fetched',
[],
'rank_math_general'
);
return [
'content' => $data['default'],
'exists' => ! empty( $data['exists'] ),
'public' => 0 !== absint( $data['public'] ),
];
}
/**
* Fetch raw data from Robots_Txt. Extracted for testability.
*
* @return array
*/
protected function get_robots_data(): array {
return Robots_Txt::get_robots_data();
}
}
@@ -0,0 +1,191 @@
<?php
/**
* Ability: rank-math/get-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-settings ability.
*/
class Get_Settings extends Abstract_Ability {
/**
* Keys stripped from the general section before returning to AI — contain credentials or internal state.
*/
const SENSITIVE_GENERAL_KEYS = [
'facebook_secret',
'console_profile',
'searchConsole',
'analyticsData',
'analytics',
'console_caching_control',
];
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'manage_options' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Get settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns the full normalized Rank Math settings snapshot: all four sections (general, titles, sitemap, instant_indexing), active module status, and auto-update state. Call this first in any AI configuration flow to understand what is already configured before making changes.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'sections' => [
'type' => 'array',
'description' => esc_html__( 'Return only these top-level sections. Omit to return the full snapshot.', 'seo-by-rank-math' ),
'items' => [
'type' => 'string',
'enum' => [ 'general', 'titles', 'sitemap', 'instant_indexing', 'modules', 'auto_update' ],
],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( true ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$settings = rank_math()->settings->all();
foreach ( self::SENSITIVE_GENERAL_KEYS as $key ) {
unset( $settings['general'][ $key ] );
}
$settings['modules'] = $this->get_module_status();
$settings['auto_update'] = $this->get_auto_update_setting();
if ( ! empty( $input['sections'] ) ) {
$settings = array_intersect_key( $settings, array_fill_keys( $input['sections'], true ) );
}
rank_math()->tracking->track_ability_executed(
'Settings Fetched',
[ 'sections' => array_keys( $settings ) ],
'manage_options'
);
return $settings;
}
/**
* Build a map of user-facing modules with their effective active status.
*
* Excludes internal modules (always loaded, not user-toggleable) and
* skip-only entries. Modules whose dependencies are not met (disabled = true)
* are always reported as inactive regardless of the stored option value.
*
* @return array<string, bool>
*/
private function get_module_status(): array {
$active_modules = $this->get_active_modules();
$status = [];
foreach ( rank_math()->manager->modules as $slug => $module ) {
$only = $module->get( 'only' );
// Internal and skip-only modules are not user-configurable.
if ( 'internal' === $only || 'skip' === $only ) {
continue;
}
// A module whose dependency is missing is always inactive.
if ( $module->get( 'disabled', false ) ) {
$status[ $slug ] = false;
continue;
}
$status[ $slug ] = in_array( $slug, $active_modules, true );
}
return $status;
}
/**
* Whether automatic plugin updates are enabled. Extracted for testability.
*
* @return bool
*/
protected function get_auto_update_setting(): bool {
return Helper::get_auto_update_setting();
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'description' => 'Normalized plugin settings snapshot.',
'properties' => [
'general' => [
'type' => 'object',
'description' => 'General settings (rank-math-options-general). Boolean values are normalized from on/off storage strings.',
],
'titles' => [
'type' => 'object',
'description' => 'Titles & Meta settings (rank-math-options-titles).',
],
'sitemap' => [
'type' => 'object',
'description' => 'Sitemap settings (rank-math-options-sitemap).',
],
'instant_indexing' => [
'type' => 'object',
'description' => 'Instant Indexing settings (rank-math-options-instant-indexing).',
],
'modules' => [
'type' => 'object',
'description' => 'Map of all registered module slugs to their active status.',
'additionalProperties' => [ 'type' => 'boolean' ],
],
'auto_update' => [
'type' => 'boolean',
'description' => 'Whether automatic plugin updates are enabled.',
],
],
];
}
}
@@ -0,0 +1,91 @@
<?php
/**
* Ability: rank-math/get-system-status
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Status\System_Status;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-system-status ability.
*
* Delegates entirely to System_Status::get_json_data() which already
* collects Rank Math health data and WordPress core / server info.
*/
class Get_System_Status extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'manage_options' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-system-status',
[
'category' => $this->category,
'label' => esc_html__( 'Get system status', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns a structured system health snapshot identical to Status & Tools → System Status in the admin: Rank Math version, plan, DB table health, Google token status, WordPress core info, server environment, and active plugins. Call this alongside get-settings at the start of any AI configuration flow to detect environment issues before making changes.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
],
'output_schema' => [
'type' => 'object',
'description' => 'System info sections keyed by section ID (e.g. rank-math, wp-core, wp-server).',
],
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( true ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$result = $this->fetch_system_data()['systemInfo'];
rank_math()->tracking->track_ability_executed(
'System Status Fetched',
[],
'manage_options'
);
return $result;
}
/**
* Fetch raw data from System_Status. Extracted for testability.
*
* @return array
*/
protected function fetch_system_data(): array {
return System_Status::get_json_data();
}
}
@@ -0,0 +1,172 @@
<?php
/**
* Ability: rank-math/set-breadcrumb-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-breadcrumb-settings ability.
*/
class Set_Breadcrumb_Settings extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_general' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-breadcrumb-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set breadcrumb settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates breadcrumb display settings: enabling breadcrumbs, the separator, home link visibility/label/URL, a prefix before the trail, archive/search/404 label formats, ancestor category display, hiding the taxonomy name, removing the current post title, and showing the blog page. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'breadcrumbs' => [
'type' => 'boolean',
'title' => esc_html__( 'Enable Breadcrumbs', 'seo-by-rank-math' ),
'description' => esc_html__( 'Enable the Breadcrumbs feature.', 'seo-by-rank-math' ),
],
'breadcrumbs_separator' => [
'type' => 'string',
'title' => esc_html__( 'Separator Character', 'seo-by-rank-math' ),
'description' => esc_html__( 'Character to display between breadcrumb links.', 'seo-by-rank-math' ),
],
'breadcrumbs_home' => [
'type' => 'boolean',
'title' => esc_html__( 'Show Home Link', 'seo-by-rank-math' ),
'description' => esc_html__( 'Show a link to the homepage at the start of the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_home_label' => [
'type' => 'string',
'title' => esc_html__( 'Home Label', 'seo-by-rank-math' ),
'description' => esc_html__( 'Label used for the homepage link in the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_home_link' => [
'type' => 'string',
'title' => esc_html__( 'Home Link', 'seo-by-rank-math' ),
'description' => esc_html__( 'URL used for the homepage link in the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_prefix' => [
'type' => 'string',
'title' => esc_html__( 'Prefix Breadcrumb', 'seo-by-rank-math' ),
'description' => esc_html__( 'Text to show before the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_archive_format' => [
'type' => 'string',
'title' => esc_html__( 'Archive Format', 'seo-by-rank-math' ),
'description' => esc_html__( 'Label format used for archive pages in the breadcrumb trail. Include a placeholder token for the archive title.', 'seo-by-rank-math' ),
],
'breadcrumbs_search_format' => [
'type' => 'string',
'title' => esc_html__( 'Search Results Format', 'seo-by-rank-math' ),
'description' => esc_html__( 'Label format used for search results pages in the breadcrumb trail. Include a placeholder token for the search query.', 'seo-by-rank-math' ),
],
'breadcrumbs_404_label' => [
'type' => 'string',
'title' => esc_html__( '404 Label', 'seo-by-rank-math' ),
'description' => esc_html__( 'Label used for the 404 error item in the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_remove_post_title' => [
'type' => 'boolean',
'title' => esc_html__( 'Hide Post Title', 'seo-by-rank-math' ),
'description' => esc_html__( 'Hide the current post/page title from the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_ancestor_categories' => [
'type' => 'boolean',
'title' => esc_html__( 'Show Category(s)', 'seo-by-rank-math' ),
'description' => esc_html__( 'If the category is a child category, show all ancestor categories in the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_hide_taxonomy_name' => [
'type' => 'boolean',
'title' => esc_html__( 'Hide Taxonomy Name', 'seo-by-rank-math' ),
'description' => esc_html__( 'Hide the current taxonomy term name from the breadcrumb trail.', 'seo-by-rank-math' ),
],
'breadcrumbs_blog_page' => [
'type' => 'boolean',
'title' => esc_html__( 'Show Blog Page', 'seo-by-rank-math' ),
'description' => esc_html__( 'Show the blog page in the breadcrumb trail. Only applies when a static homepage is set.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$general = $this->get_general_option();
$this->apply_toggle_fields(
$general,
$input,
[
'breadcrumbs',
'breadcrumbs_home',
'breadcrumbs_remove_post_title',
'breadcrumbs_ancestor_categories',
'breadcrumbs_hide_taxonomy_name',
'breadcrumbs_blog_page',
]
);
foreach ( [ 'breadcrumbs_separator', 'breadcrumbs_home_label', 'breadcrumbs_prefix', 'breadcrumbs_archive_format', 'breadcrumbs_search_format', 'breadcrumbs_404_label' ] as $field ) {
if ( isset( $input[ $field ] ) ) {
$general[ $field ] = sanitize_text_field( $input[ $field ] );
}
}
if ( isset( $input['breadcrumbs_home_link'] ) ) {
$general['breadcrumbs_home_link'] = esc_url_raw( $input['breadcrumbs_home_link'] );
}
$this->save_and_reset( $general, null, null );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Breadcrumb Settings Updated',
[ 'fields_updated' => $keys ],
'rank_math_general'
);
return [
'saved' => true,
'updated' => $keys,
];
}
}
@@ -0,0 +1,150 @@
<?php
/**
* Ability: rank-math/set-global-seo-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-global-seo-settings ability.
*/
class Set_Global_Seo_Settings extends Abstract_Ability {
/**
* Allowed values for the twitter_card_type field.
*/
const TWITTER_CARD_TYPES = [ 'summary_large_image', 'summary_card' ];
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_titles' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-global-seo-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set global SEO settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates site-wide SEO defaults: global robots meta directives, whether to noindex empty taxonomy archives, the title separator character, title capitalization, and the default Twitter card type. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'robots_global' => [
'type' => 'array',
'items' => [
'type' => 'string',
'enum' => self::ROBOTS_DIRECTIVES,
],
'description' => esc_html__( 'Global robots meta directives applied site-wide (e.g. ["index"], ["noindex","nofollow"]).', 'seo-by-rank-math' ),
],
'noindex_empty_taxonomies' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether to noindex taxonomy archives that have no posts assigned.', 'seo-by-rank-math' ),
],
'title_separator' => [
'type' => 'string',
'description' => esc_html__( 'Character used to separate parts of the SEO title (e.g. "-", "|", "&mdash;"). A custom string is also accepted.', 'seo-by-rank-math' ),
],
'capitalize_titles' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether to capitalize the first letter of every word in SEO titles.', 'seo-by-rank-math' ),
],
'twitter_card_type' => [
'type' => 'string',
'enum' => self::TWITTER_CARD_TYPES,
'description' => esc_html__( 'Default Twitter card type used when sharing content.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
if ( isset( $input['robots_global'] ) ) {
foreach ( (array) $input['robots_global'] as $value ) {
if ( ! in_array( $value, self::ROBOTS_DIRECTIVES, true ) ) {
return [
'error' => [
'code' => 'invalid_robots_global',
'message' => esc_html__( 'robots_global may only contain: index, noindex, nofollow, noarchive, noimageindex, nosnippet.', 'seo-by-rank-math' ),
],
];
}
}
}
if ( isset( $input['twitter_card_type'] ) && ! in_array( $input['twitter_card_type'], self::TWITTER_CARD_TYPES, true ) ) {
return [
'error' => [
'code' => 'invalid_twitter_card_type',
'message' => esc_html__( 'twitter_card_type must be either "summary_large_image" or "summary_card".', 'seo-by-rank-math' ),
],
];
}
$titles = $this->get_titles_option();
if ( isset( $input['robots_global'] ) ) {
$titles['robots_global'] = array_map( 'sanitize_text_field', (array) $input['robots_global'] );
}
$this->apply_toggle_fields( $titles, $input, [ 'noindex_empty_taxonomies', 'capitalize_titles' ] );
if ( isset( $input['title_separator'] ) ) {
$titles['title_separator'] = sanitize_text_field( $input['title_separator'] );
}
if ( isset( $input['twitter_card_type'] ) ) {
$titles['twitter_card_type'] = sanitize_text_field( $input['twitter_card_type'] );
}
$this->save_and_reset( null, $titles, null );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Global SEO Settings Updated',
[ 'fields_updated' => $keys ],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $keys,
];
}
}
@@ -0,0 +1,189 @@
<?php
/**
* Ability: rank-math/set-homepage-seo
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-homepage-seo ability.
*
* Automatically detects whether the homepage is a static page or the latest-posts
* feed and writes to the appropriate storage in each case:
*/
class Set_Homepage_Seo extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_titles' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-homepage-seo',
[
'category' => $this->category,
'label' => esc_html__( 'Set homepage SEO', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates the SEO title, meta description, and focus keyword for the site homepage. Automatically detects whether the homepage is a static page or a latest-posts feed and writes to the correct storage in each case. Call get-settings first to see current homepage values. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'title' => [
'type' => 'string',
'title' => esc_html__( 'SEO Title', 'seo-by-rank-math' ),
'description' => esc_html__( 'SEO title for the homepage. Supports Rank Math title variables (e.g. %sitename%, %sep%, %sitedesc%). For static-page homepages, stored as post meta; for latest-posts homepages, stored in Titles & Meta settings.', 'seo-by-rank-math' ), //phpcs:ignore WordPress.WP.I18n
],
'description' => [
'type' => 'string',
'title' => esc_html__( 'Meta Description', 'seo-by-rank-math' ),
'description' => esc_html__( 'Meta description for the homepage. For static-page homepages, stored as post meta; for latest-posts homepages, stored in Titles & Meta settings.', 'seo-by-rank-math' ),
],
'focus_keyword' => [
'type' => 'string',
'title' => esc_html__( 'Focus Keyword', 'seo-by-rank-math' ),
'description' => esc_html__( 'Primary focus keyword for the homepage. Only applicable when the homepage is a static page — ignored for latest-posts homepages.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
if ( empty( $input ) ) {
return [
'error' => [
'code' => 'no_fields',
'message' => esc_html__( 'No fields provided. Pass at least one of: title, description, focus_keyword.', 'seo-by-rank-math' ),
],
];
}
if ( 'page' === get_option( 'show_on_front' ) ) {
return $this->update_static_page( $input );
}
return $this->update_latest_posts( $input );
}
/**
* Write title/description post meta on the static front page.
*
* @param array $input Ability input.
* @return array
*/
private function update_static_page( array $input ): array {
$page_id = (int) get_option( 'page_on_front' );
if ( ! $page_id ) {
return [
'error' => [
'code' => 'no_front_page',
'message' => esc_html__( 'show_on_front is set to "page" but no front page is assigned (page_on_front is empty). Assign a static front page under WP Dashboard > Settings > Reading.', 'seo-by-rank-math' ),
],
];
}
$updated = [];
if ( isset( $input['title'] ) ) {
update_post_meta( $page_id, 'rank_math_title', sanitize_text_field( $input['title'] ) );
$updated[] = 'title';
}
if ( isset( $input['description'] ) ) {
update_post_meta( $page_id, 'rank_math_description', sanitize_textarea_field( $input['description'] ) );
$updated[] = 'description';
}
if ( isset( $input['focus_keyword'] ) ) {
update_post_meta( $page_id, 'rank_math_focus_keyword', sanitize_text_field( $input['focus_keyword'] ) );
$updated[] = 'focus_keyword';
}
rank_math()->tracking->track_ability_executed(
'Homepage SEO Updated',
[
'homepage_type' => 'static_page',
'page_id' => $page_id,
'fields_updated' => $updated,
],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $updated,
];
}
/**
* Write title/description into the Titles & Meta settings for the
* latest-posts homepage.
*
* @param array $input Ability input.
* @return array
*/
private function update_latest_posts( array $input ): array {
$titles = $this->get_titles_option();
$updated = [];
if ( isset( $input['title'] ) ) {
$titles['homepage_title'] = sanitize_text_field( $input['title'] );
$updated[] = 'title';
}
if ( isset( $input['description'] ) ) {
$titles['homepage_description'] = sanitize_textarea_field( $input['description'] );
$updated[] = 'description';
}
$this->save_and_reset( null, $titles, null );
rank_math()->tracking->track_ability_executed(
'Homepage SEO Updated',
[
'homepage_type' => 'latest_posts',
'fields_updated' => $updated,
],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $updated,
];
}
}
@@ -0,0 +1,137 @@
<?php
/**
* Ability: rank-math/set-link-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-link-settings ability.
*/
class Set_Link_Settings extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_general' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-link-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set link settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates site-wide link behavior: nofollow for external and image links, opening external links in a new tab, nofollow domain allow/exclude lists, category base stripping, and attachment page redirects. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'nofollow_external_links' => [
'type' => 'boolean',
'title' => esc_html__( 'Nofollow External Links', 'seo-by-rank-math' ),
'description' => esc_html__( 'Automatically add rel="nofollow" to external links in content.', 'seo-by-rank-math' ),
],
'new_window_external_links' => [
'type' => 'boolean',
'title' => esc_html__( 'Open External Links in New Tab/Window', 'seo-by-rank-math' ),
'description' => esc_html__( 'Automatically add target="_blank" to external links in content.', 'seo-by-rank-math' ),
],
'nofollow_image_links' => [
'type' => 'boolean',
'title' => esc_html__( 'Nofollow Image File Links', 'seo-by-rank-math' ),
'description' => esc_html__( 'Automatically add rel="nofollow" to links pointing to external image files.', 'seo-by-rank-math' ),
],
'nofollow_domains' => [
'type' => 'string',
'title' => esc_html__( 'Nofollow Domains', 'seo-by-rank-math' ),
'description' => esc_html__( 'Newline-separated list of domains to nofollow. If empty, nofollow applies to all external domains (when enabled). Only takes effect when nofollow_external_links or nofollow_image_links is also enabled — hidden in the UI otherwise.', 'seo-by-rank-math' ),
],
'nofollow_exclude_domains' => [
'type' => 'string',
'title' => esc_html__( 'Nofollow Exclude Domains', 'seo-by-rank-math' ),
'description' => esc_html__( 'Newline-separated list of domains to exclude from nofollow. Only takes effect when nofollow_external_links or nofollow_image_links is also enabled — hidden in the UI otherwise.', 'seo-by-rank-math' ),
],
'strip_category_base' => [
'type' => 'boolean',
'title' => esc_html__( 'Strip Category Base', 'seo-by-rank-math' ),
'description' => esc_html__( 'Remove /category/ from category archive URLs.', 'seo-by-rank-math' ),
],
'attachment_redirect_urls' => [
'type' => 'boolean',
'title' => esc_html__( 'Redirect Attachments', 'seo-by-rank-math' ),
'description' => esc_html__( 'Redirect attachment page URLs to the post they appear in.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$general = $this->get_general_option();
$this->apply_toggle_fields(
$general,
$input,
[
'nofollow_external_links',
'new_window_external_links',
'nofollow_image_links',
'strip_category_base',
'attachment_redirect_urls',
]
);
foreach ( [ 'nofollow_domains', 'nofollow_exclude_domains' ] as $field ) {
if ( isset( $input[ $field ] ) ) {
$general[ $field ] = sanitize_textarea_field( $input[ $field ] );
}
}
$this->save_and_reset( $general, null, null );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Link Settings Updated',
[ 'fields_updated' => $keys ],
'rank_math_general'
);
return [
'saved' => true,
'updated' => $keys,
];
}
}
@@ -0,0 +1,179 @@
<?php
/**
* Ability: rank-math/set-module-status
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-module-status ability.
*/
class Set_Module_Status extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'manage_options' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-module-status',
[
'category' => $this->category,
'label' => esc_html__( 'Set module status', 'seo-by-rank-math' ),
'description' => esc_html__(
'Enables or disables Rank Math modules (e.g. sitemap, redirections, 404-monitor, rich-snippet). Only provided module slugs are changed; omitted modules keep their current state. Modules with unmet dependencies (e.g. Video Sitemap requires Sitemap and Schema) cannot be enabled until their dependencies are active or enabled in the same call. Modules whose external requirements are not met (e.g. WooCommerce module without the WooCommerce plugin active) cannot be enabled at all.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'modules' ],
'properties' => [
'modules' => [
'type' => 'object',
'title' => esc_html__( 'Modules', 'seo-by-rank-math' ),
'description' => esc_html__( 'Map of module slug to desired active state. Call get-settings first to see the full list of registered module slugs and their current status.', 'seo-by-rank-math' ),
'additionalProperties' => [ 'type' => 'boolean' ],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true, 'List of module slugs whose status was changed.' ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$requested = isset( $input['modules'] ) && is_array( $input['modules'] ) ? $input['modules'] : [];
if ( empty( $requested ) ) {
return [
'error' => [
'code' => 'missing_modules',
'message' => esc_html__( 'modules must be a non-empty map of module slug to boolean.', 'seo-by-rank-math' ),
],
];
}
$registered = $this->get_registered_modules();
$active = $this->get_active_modules();
$to_update = [];
foreach ( $requested as $slug => $enable ) {
if ( ! array_key_exists( $slug, $registered ) ) {
return [
'error' => [
'code' => 'invalid_module',
'message' => sprintf(
/* translators: module slug */
esc_html__( 'Unknown module: %s', 'seo-by-rank-math' ),
esc_html( $slug )
),
],
];
}
if ( $enable ) {
if ( $registered[ $slug ]->is_disabled() ) {
$disabled_text = $registered[ $slug ]->get( 'disabled_text' );
if ( empty( $disabled_text ) ) {
$disabled_text = sprintf(
/* translators: module slug */
esc_html__( 'Cannot enable "%s" — its requirements are not met.', 'seo-by-rank-math' ),
esc_html( $slug )
);
}
return [
'error' => [
'code' => 'module_disabled',
'message' => $disabled_text,
],
];
}
foreach ( $registered[ $slug ]->get_dependencies() as $dependency ) {
$dependency_met = in_array( $dependency, $active, true )
|| ( isset( $requested[ $dependency ] ) && $requested[ $dependency ] );
if ( ! $dependency_met ) {
return [
'error' => [
'code' => 'unmet_dependency',
'message' => sprintf(
/* translators: 1: module slug, 2: required module slug */
esc_html__( 'Cannot enable "%1$s" — it requires the "%2$s" module to be active or enabled in the same call.', 'seo-by-rank-math' ),
esc_html( $slug ),
esc_html( $dependency )
),
],
];
}
}
}
$to_update[ $slug ] = $enable ? 'on' : 'off';
}
Helper::update_modules( $to_update );
foreach ( $to_update as $slug => $state ) {
if ( 'off' === $state && in_array( $slug, [ 'sitemap', 'llms-txt' ], true ) ) {
delete_option( 'rewrite_rules' );
}
do_action( 'rank_math/module_changed', $slug, $state );
}
$keys = array_keys( $requested );
rank_math()->tracking->track_ability_executed(
'Module Status Updated',
[ 'modules_updated' => $keys ],
'manage_options'
);
return [
'saved' => true,
'updated' => $keys,
];
}
/**
* Registered modules keyed by slug. Extracted for testability.
*
* @return array<string, \RankMath\Module\Module>
*/
protected function get_registered_modules(): array {
return rank_math()->manager->modules;
}
}
@@ -0,0 +1,90 @@
<?php
/**
* Ability: rank-math/set-plugin-preferences
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-plugin-preferences ability.
*/
class Set_Plugin_Preferences extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'manage_options' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-plugin-preferences',
[
'category' => $this->category,
'label' => esc_html__( 'Set plugin preferences', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates Rank Math plugin-level preferences that are not part of a settings section. Currently supports toggling automatic plugin updates.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'enable_auto_update' ],
'properties' => [
'enable_auto_update' => [
'type' => 'boolean',
'title' => esc_html__( 'Enable Automatic Updates', 'seo-by-rank-math' ),
'description' => esc_html__( 'Whether WordPress should automatically install new Rank Math plugin updates.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$enable = ! empty( $input['enable_auto_update'] );
Helper::toggle_auto_update_setting( $enable ? 'on' : 'off' );
rank_math()->tracking->track_ability_executed(
'Plugin Preferences Updated',
[ 'enable_auto_update' => $enable ],
'manage_options'
);
return [
'saved' => true,
'updated' => [ 'enable_auto_update' ],
];
}
}
@@ -0,0 +1,224 @@
<?php
/**
* Ability: rank-math/set-post-type-seo-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-post-type-seo-settings ability.
*/
class Set_Post_Type_Seo_Settings extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_titles' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-post-type-seo-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set post type SEO settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates per-post-type SEO defaults: default title/description templates, default Schema type, default article type, custom robots meta, and whether to show SEO controls on the editor screen. Accepts a map keyed by post type slug; only provided post types and fields are changed.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'required' => [ 'post_types' ],
'properties' => [
'post_types' => [
'type' => 'object',
'title' => esc_html__( 'Post Types', 'seo-by-rank-math' ),
'description' => esc_html__( 'Map of post type slug to its SEO settings. Call get-settings first to see registered post type slugs.', 'seo-by-rank-math' ),
'additionalProperties' => [
'type' => 'object',
'properties' => [
'title' => [
'type' => 'string',
'title' => esc_html__( 'Single Title', 'seo-by-rank-math' ),
'description' => esc_html__( 'Default title tag for single pages of this post type. Supports Rank Math title variables.', 'seo-by-rank-math' ),
],
'description' => [
'type' => 'string',
'title' => esc_html__( 'Single Description', 'seo-by-rank-math' ),
'description' => esc_html__( 'Default meta description for single pages of this post type. Supports Rank Math variables.', 'seo-by-rank-math' ),
],
'default_rich_snippet' => [
'type' => 'string',
'title' => esc_html__( 'Schema Type', 'seo-by-rank-math' ),
'description' => esc_html__( 'Default Schema type slug for new posts of this type (e.g. "off", "article", "product", "event"). Call get-settings first or see the Schema Type list in WP Admin for valid values — the list varies per post type and active modules.', 'seo-by-rank-math' ),
],
'default_article_type' => [
'type' => 'string',
'enum' => [ 'Article', 'BlogPosting', 'NewsArticle' ],
'title' => esc_html__( 'Article Type', 'seo-by-rank-math' ),
'description' => esc_html__( 'Default article schema sub-type. Only used when default_rich_snippet is "article".', 'seo-by-rank-math' ),
],
'custom_robots' => [
'type' => 'boolean',
'title' => esc_html__( 'Custom Robots Meta', 'seo-by-rank-math' ),
'description' => esc_html__( 'Whether to use custom robots meta values for this post type instead of the Global Meta default.', 'seo-by-rank-math' ),
],
'robots' => [
'type' => 'array',
'items' => [
'type' => 'string',
'enum' => self::ROBOTS_DIRECTIVES,
],
'title' => esc_html__( 'Robots Meta', 'seo-by-rank-math' ),
'description' => esc_html__( 'Custom robots meta values for this post type. Only takes effect when custom_robots is enabled.', 'seo-by-rank-math' ),
],
'add_meta_box' => [
'type' => 'boolean',
'title' => esc_html__( 'Add SEO Controls', 'seo-by-rank-math' ),
'description' => esc_html__( 'Whether to add SEO controls to the editor screen for posts of this type.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true, 'List of "post_type.field" identifiers that were updated.' ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$post_types = isset( $input['post_types'] ) && is_array( $input['post_types'] ) ? $input['post_types'] : [];
if ( empty( $post_types ) ) {
return [
'error' => [
'code' => 'missing_post_types',
'message' => esc_html__( 'post_types must be a non-empty map of post type slug to settings.', 'seo-by-rank-math' ),
],
];
}
$accessible = $this->get_accessible_post_types();
foreach ( $post_types as $post_type => $fields ) {
if ( ! in_array( $post_type, $accessible, true ) ) {
return [
'error' => [
'code' => 'invalid_post_type',
'message' => sprintf(
/* translators: post type slug */
esc_html__( 'Unknown or inaccessible post type: %s', 'seo-by-rank-math' ),
esc_html( $post_type )
),
],
];
}
if ( isset( $fields['robots'] ) ) {
foreach ( (array) $fields['robots'] as $value ) {
if ( ! in_array( $value, self::ROBOTS_DIRECTIVES, true ) ) {
return [
'error' => [
'code' => 'invalid_robots',
'message' => esc_html__( 'robots may only contain: index, noindex, nofollow, noarchive, noimageindex, nosnippet.', 'seo-by-rank-math' ),
],
];
}
}
}
if ( isset( $fields['default_article_type'] ) && ! in_array( $fields['default_article_type'], [ 'Article', 'BlogPosting', 'NewsArticle' ], true ) ) {
return [
'error' => [
'code' => 'invalid_article_type',
'message' => esc_html__( 'default_article_type must be one of: Article, BlogPosting, NewsArticle.', 'seo-by-rank-math' ),
],
];
}
}
$titles = $this->get_titles_option();
$updated = [];
foreach ( $post_types as $post_type => $fields ) {
$prefix = "pt_{$post_type}_";
foreach ( [ 'title', 'description' ] as $field ) {
if ( isset( $fields[ $field ] ) ) {
$titles[ $prefix . $field ] = sanitize_text_field( $fields[ $field ] );
$updated[] = "{$post_type}.{$field}";
}
}
if ( isset( $fields['default_rich_snippet'] ) ) {
$titles[ $prefix . 'default_rich_snippet' ] = sanitize_text_field( $fields['default_rich_snippet'] );
$updated[] = "{$post_type}.default_rich_snippet";
}
if ( isset( $fields['default_article_type'] ) ) {
$titles[ $prefix . 'default_article_type' ] = $fields['default_article_type'];
$updated[] = "{$post_type}.default_article_type";
}
if ( isset( $fields['custom_robots'] ) ) {
$titles[ $prefix . 'custom_robots' ] = $fields['custom_robots'] ? 'on' : 'off';
$updated[] = "{$post_type}.custom_robots";
}
if ( isset( $fields['robots'] ) ) {
$titles[ $prefix . 'robots' ] = array_map( 'sanitize_text_field', (array) $fields['robots'] );
$updated[] = "{$post_type}.robots";
}
if ( isset( $fields['add_meta_box'] ) ) {
$titles[ $prefix . 'add_meta_box' ] = $fields['add_meta_box'] ? 'on' : 'off';
$updated[] = "{$post_type}.add_meta_box";
}
}
$this->save_and_reset( null, $titles, null );
rank_math()->tracking->track_ability_executed(
'Post Type SEO Settings Updated',
[
'post_types' => array_keys( $post_types ),
'fields_updated' => $updated,
],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $updated,
];
}
}
@@ -0,0 +1,219 @@
<?php
/**
* Ability: rank-math/set-sitemap-settings
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-sitemap-settings ability.
*/
class Set_Sitemap_Settings extends Abstract_Ability {
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_sitemap' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-sitemap-settings',
[
'category' => $this->category,
'label' => esc_html__( 'Set sitemap settings', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates XML sitemap settings: links per sitemap page, image inclusion, excluded post/term IDs, author archive inclusion, and per-post-type/per-taxonomy sitemap inclusion. All fields are optional — omitted fields keep their current stored value. Requires the sitemap module to be active; enable it first with set-module-status if needed.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'items_per_page' => [
'type' => 'integer',
'title' => esc_html__( 'Links Per Sitemap', 'seo-by-rank-math' ),
'description' => esc_html__( 'Max number of links on each sitemap page.', 'seo-by-rank-math' ),
],
'include_images' => [
'type' => 'boolean',
'title' => esc_html__( 'Images in Sitemaps', 'seo-by-rank-math' ),
'description' => esc_html__( 'Include reference to images from the post content in sitemaps.', 'seo-by-rank-math' ),
],
'include_featured_image' => [
'type' => 'boolean',
'title' => esc_html__( 'Include Featured Images', 'seo-by-rank-math' ),
'description' => esc_html__( 'Include the Featured Image too, even if it does not appear directly in the post content. Only takes effect when include_images is also enabled.', 'seo-by-rank-math' ),
],
'exclude_posts' => [
'type' => 'string',
'title' => esc_html__( 'Exclude Posts', 'seo-by-rank-math' ),
'description' => esc_html__( 'Comma-separated post IDs to exclude from the sitemap. Applies to all post types.', 'seo-by-rank-math' ),
],
'exclude_terms' => [
'type' => 'string',
'title' => esc_html__( 'Exclude Terms', 'seo-by-rank-math' ),
'description' => esc_html__( 'Comma-separated term IDs to exclude from the sitemap. Applies to all taxonomies.', 'seo-by-rank-math' ),
],
'authors_sitemap' => [
'type' => 'boolean',
'title' => esc_html__( 'Include Authors in Sitemap', 'seo-by-rank-math' ),
'description' => esc_html__( 'Include author archives in the XML sitemap.', 'seo-by-rank-math' ),
],
'post_types' => [
'type' => 'object',
'title' => esc_html__( 'Post Types', 'seo-by-rank-math' ),
'description' => esc_html__( 'Map of post type slug to whether it should be included in the XML sitemap. Call get-settings first to see registered post type sitemap status.', 'seo-by-rank-math' ),
'additionalProperties' => [ 'type' => 'boolean' ],
],
'taxonomies' => [
'type' => 'object',
'title' => esc_html__( 'Taxonomies', 'seo-by-rank-math' ),
'description' => esc_html__( 'Map of taxonomy slug to whether it should be included in the XML sitemap.', 'seo-by-rank-math' ),
'additionalProperties' => [ 'type' => 'boolean' ],
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true, 'List of top-level field names that were updated.' ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
if ( isset( $input['post_types'] ) ) {
$accessible_post_types = $this->get_accessible_post_types();
foreach ( array_keys( $input['post_types'] ) as $post_type ) {
if ( ! in_array( $post_type, $accessible_post_types, true ) ) {
return [
'error' => [
'code' => 'invalid_post_type',
'message' => sprintf(
/* translators: post type slug */
esc_html__( 'Unknown or inaccessible post type: %s', 'seo-by-rank-math' ),
esc_html( $post_type )
),
],
];
}
}
}
if ( isset( $input['taxonomies'] ) ) {
$accessible_taxonomies = $this->get_accessible_taxonomies();
foreach ( array_keys( $input['taxonomies'] ) as $taxonomy ) {
if ( ! in_array( $taxonomy, $accessible_taxonomies, true ) ) {
return [
'error' => [
'code' => 'invalid_taxonomy',
'message' => sprintf(
/* translators: taxonomy slug */
esc_html__( 'Unknown or inaccessible taxonomy: %s', 'seo-by-rank-math' ),
esc_html( $taxonomy )
),
],
];
}
}
}
$sitemap = $this->get_sitemap_option();
if ( isset( $input['items_per_page'] ) ) {
$sitemap['items_per_page'] = (string) absint( $input['items_per_page'] );
}
$this->apply_toggle_fields(
$sitemap,
$input,
[ 'include_images', 'include_featured_image', 'authors_sitemap' ]
);
foreach ( [ 'exclude_posts', 'exclude_terms' ] as $field ) {
if ( isset( $input[ $field ] ) ) {
$sitemap[ $field ] = sanitize_text_field( $input[ $field ] );
}
}
if ( isset( $input['post_types'] ) ) {
foreach ( $input['post_types'] as $post_type => $enabled ) {
$sitemap[ "pt_{$post_type}_sitemap" ] = $enabled ? 'on' : 'off';
}
}
if ( isset( $input['taxonomies'] ) ) {
foreach ( $input['taxonomies'] as $taxonomy => $enabled ) {
$sitemap[ "tax_{$taxonomy}_sitemap" ] = $enabled ? 'on' : 'off';
}
}
$this->save_and_reset( null, null, $sitemap );
/**
* Fires after set-sitemap-settings saves its FREE fields, so PRO can persist
* its own sitemap fields (news_sitemap_publication_name, video_sitemap_post_type,
* hide_video_sitemap, local_sitemap) from the same input.
*
* @param array $input Raw ability input.
*/
do_action( 'rank_math/abilities/set_sitemap_settings/after_save', $input );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Sitemap Settings Updated',
[ 'fields_updated' => $keys ],
'rank_math_sitemap'
);
return [
'saved' => true,
'updated' => $keys,
];
}
/**
* Current raw sitemap option. Extracted for testability.
*
* @return array
*/
protected function get_sitemap_option(): array {
return (array) get_option( 'rank-math-options-sitemap', [] );
}
/**
* Accessible taxonomy slugs. Extracted for testability.
*
* @return array<int, string>
*/
protected function get_accessible_taxonomies(): array {
return array_keys( Helper::get_accessible_taxonomies() );
}
}
@@ -0,0 +1,161 @@
<?php
/**
* Ability: rank-math/set-website-identity
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Helper;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/set-website-identity ability.
*/
class Set_Website_Identity extends Abstract_Ability {
/**
* Allowed values for the knowledgegraph_type field.
*/
const KNOWLEDGEGRAPH_TYPES = [ 'person', 'company' ];
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
parent::__construct( $category, $shared_meta, 'rank_math_titles' );
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/set-website-identity',
[
'category' => $this->category,
'label' => esc_html__( 'Set website identity', 'seo-by-rank-math' ),
'description' => esc_html__(
'Updates the site\'s Knowledge Graph identity used by Rank Math for schema and social markup: knowledge graph type (person/company), website name, alternate name, knowledge graph name, organization description, business type, and site URL override. All fields are optional — omitted fields keep their current stored value.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [
'knowledgegraph_type' => [
'type' => 'string',
'enum' => self::KNOWLEDGEGRAPH_TYPES,
'description' => esc_html__( 'Whether the site represents a person or a company/organization.', 'seo-by-rank-math' ),
],
'website_name' => [
'type' => 'string',
'description' => esc_html__( 'The website name used in schema and social markup.', 'seo-by-rank-math' ),
],
'website_alternate_name' => [
'type' => 'string',
'description' => esc_html__( 'An alternate name for the website.', 'seo-by-rank-math' ),
],
'knowledgegraph_name' => [
'type' => 'string',
'description' => esc_html__( 'The person or organization name used in the Knowledge Graph.', 'seo-by-rank-math' ),
],
'organization_description' => [
'type' => 'string',
'description' => esc_html__( 'Description of the organization. Only used when knowledgegraph_type is "company".', 'seo-by-rank-math' ),
],
'local_business_type' => [
'type' => 'string',
'description' => esc_html__( 'Schema.org business type slug (e.g. "Restaurant", "LegalService", "Organization"), spaces removed. Only used when knowledgegraph_type is "company". Call get-settings first or see the Local SEO business type list in WP Admin for valid values.', 'seo-by-rank-math' ),
],
'url' => [
'type' => 'string',
'description' => esc_html__( 'Site URL override used in Knowledge Graph markup.', 'seo-by-rank-math' ),
],
],
'additionalProperties' => false,
],
'output_schema' => $this->write_success_schema( true ),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => $this->build_meta( false ),
]
);
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
if ( isset( $input['knowledgegraph_type'] ) && ! in_array( $input['knowledgegraph_type'], self::KNOWLEDGEGRAPH_TYPES, true ) ) {
return [
'error' => [
'code' => 'invalid_knowledgegraph_type',
'message' => esc_html__( 'knowledgegraph_type must be either "person" or "company".', 'seo-by-rank-math' ),
],
];
}
if ( isset( $input['local_business_type'] ) && ! array_key_exists( $input['local_business_type'], $this->get_business_types() ) ) {
return [
'error' => [
'code' => 'invalid_local_business_type',
'message' => esc_html__( 'local_business_type is not a recognized Schema.org business type slug.', 'seo-by-rank-math' ),
],
];
}
$titles = $this->get_titles_option();
foreach ( [ 'knowledgegraph_type', 'website_name', 'website_alternate_name', 'knowledgegraph_name', 'local_business_type' ] as $field ) {
if ( isset( $input[ $field ] ) ) {
$titles[ $field ] = sanitize_text_field( $input[ $field ] );
}
}
if ( isset( $input['url'] ) ) {
$titles['url'] = esc_url_raw( $input['url'] );
}
if ( isset( $input['organization_description'] ) ) {
$titles['organization_description'] = wp_kses_post( $input['organization_description'] );
}
$this->save_and_reset( null, $titles, null );
$keys = array_keys( $input );
rank_math()->tracking->track_ability_executed(
'Website Identity Updated',
[ 'fields_updated' => $keys ],
'rank_math_titles'
);
return [
'saved' => true,
'updated' => $keys,
];
}
/**
* Valid Schema.org business type slugs. Extracted for testability.
*
* @return array<string, string>
*/
protected function get_business_types(): array {
return Helper::choices_business_types();
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Subscriber for Settings abilities.
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Settings
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Settings;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Settings ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Settings abilities.
*/
const CATEGORY_SLUG = 'rank-math-settings';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_abilities' );
}
/**
* Register the Settings ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Settings', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to read and configure Rank Math plugin settings.', 'seo-by-rank-math' ),
]
);
}
/**
* Register all Settings abilities.
*
* @return void
*/
public function register_abilities(): void {
$classes = [
Get_Settings::class,
Get_System_Status::class,
Get_Llms_Txt::class,
Get_Robots_Txt::class,
Set_Website_Identity::class,
Set_Global_Seo_Settings::class,
Set_Homepage_Seo::class,
Set_Link_Settings::class,
Set_Module_Status::class,
Set_Sitemap_Settings::class,
Set_Plugin_Preferences::class,
Set_Post_Type_Seo_Settings::class,
Set_Breadcrumb_Settings::class,
];
foreach ( $classes as $class ) {
( new $class( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,335 @@
<?php
/**
* Ability: rank-math/get-sitemap-status
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Sitemap
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Sitemap;
use RankMath\Abilities\Ability_Interface;
use RankMath\Helper;
use RankMath\Sitemap\Generator;
use RankMath\Sitemap\Router;
use RankMath\Sitemap\Sitemap;
use RankMath\Sitemap\Providers\Post_Type as Post_Type_Provider;
use RankMath\Sitemap\Providers\Taxonomy as Taxonomy_Provider;
use RankMath\Sitemap\Providers\Author as Author_Provider;
defined( 'ABSPATH' ) || exit;
/**
* Registers and executes the rank-math/get-sitemap-status ability.
*/
class Get_Sitemap_Status implements Ability_Interface {
/**
* Ability category slug.
*
* @var string
*/
private $category;
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param string $category Ability category slug.
* @param array $shared_meta Shared meta args.
*/
public function __construct( string $category, array $shared_meta ) {
$this->category = $category;
$this->shared_meta = $shared_meta;
}
/**
* Register the ability with the WordPress Abilities API.
*
* @return void
*/
public function register(): void {
\wp_register_ability(
'rank-math/get-sitemap-status',
[
'category' => $this->category,
'label' => esc_html__( 'Get sitemap status', 'seo-by-rank-math' ),
'description' => esc_html__(
'Returns whether the XML sitemap is enabled, the sitemap index URL, and the active sitemap types (post types, taxonomies, and the Local SEO sitemap, when active) with their URLs and estimated entry counts.',
'seo-by-rank-math'
),
'input_schema' => [
'type' => 'object',
'default' => [],
'properties' => [],
'additionalProperties' => false,
],
'output_schema' => $this->output_schema(),
'permission_callback' => [ $this, 'check_permissions' ],
'execute_callback' => [ $this, 'execute' ],
'meta' => array_merge(
$this->shared_meta,
[
'annotations' => [
'readonly' => true,
'destructive' => false,
'idempotent' => true,
],
]
),
]
);
}
/**
* Check if the current user has permission to execute this ability.
*
* @return bool
*/
public function check_permissions(): bool {
return current_user_can( 'rank_math_sitemap' );
}
/**
* Execute the ability.
*
* @param array $input Ability input arguments.
* @return array
*/
public function execute( array $input = [] ): array {
$enabled = Helper::is_module_active( 'sitemap' );
$result = [
'enabled' => $enabled,
'index_url' => Router::get_base_url( Sitemap::get_sitemap_index_slug() . '.xml' ),
'sitemaps' => $this->get_sitemaps(),
];
rank_math()->tracking->track_ability_executed(
'Sitemap Status Fetched',
[
'enabled' => $enabled,
'sitemaps_count' => count( $result['sitemaps'] ),
],
'rank_math_sitemap'
);
return $result;
}
/**
* Build the list of active sitemap types with their URL and estimated entry count.
*
* Reuses the real Generator's provider list, so PRO types (e.g. news/video)
* show up automatically. Local SEO's `local-sitemap.xml` isn't a Provider
* though, so it's captured separately via get_non_provider_entries().
*
* @return array
*/
private function get_sitemaps(): array {
$max_entries = absint( Helper::get_settings( 'sitemap.items_per_page', 100 ) );
$providers = ( new Generator() )->providers;
$sitemaps = [];
foreach ( $providers as $provider ) {
$sitemaps = array_merge( $sitemaps, $this->build_sitemap_entries( $provider, $max_entries ) );
}
$local_sitemap = $this->get_local_sitemap();
if ( null !== $local_sitemap ) {
$sitemaps[] = $local_sitemap;
}
return array_merge( $sitemaps, $this->get_non_provider_entries() );
}
/**
* Capture sitemap entries added outside the Provider system, via the
* `rank_math/sitemap/index` filter (currently only Local SEO's KML_File).
*
* The 'local' type is excluded here because get_local_sitemap() already
* builds that entry with an accurate location count; KML_File::add_local_sitemap()
* fires this same filter internally, so without the exclusion the local
* sitemap would be added twice.
*
* @return array
*/
private function get_non_provider_entries(): array {
$entries = [];
$capture = function ( $item, $label, $type_slug = null ) use ( &$entries ) {
$type = ( is_string( $type_slug ) && '' !== $type_slug ) ? $type_slug : $label;
if ( ! empty( $item['loc'] ) && 'local' !== $type ) {
$entries[] = [
'type' => $type,
'url' => $item['loc'],
'estimated_count' => 1,
];
}
return $item;
};
add_filter( 'rank_math/sitemap/index/entry', $capture, 10, 3 );
apply_filters( 'rank_math/sitemap/index', '' );
remove_filter( 'rank_math/sitemap/index/entry', $capture, 10 );
return $entries;
}
/**
* Build sitemap entries for a single provider.
*
* Get_index_links() only returns {loc, lastmod}, so type and page number
* are captured via the `sitemap/index/entry` filter it fires internally.
* Per-page counts use each provider's own safe public method instead of
* get_sitemap_links(), which can die() via Sitemap::maybe_redirect() when
* called outside an actual sitemap page request.
*
* @param object $provider Sitemap provider instance.
* @param int $max_entries Entries per sitemap page.
* @return array
*/
private function build_sitemap_entries( $provider, int $max_entries ): array {
$entries = [];
$capture = function ( $item, $label, $type_slug = null ) use ( &$entries ) {
if ( ! empty( $item['loc'] ) ) {
$entries[] = [
'type' => ( is_string( $type_slug ) && '' !== $type_slug ) ? $type_slug : $label,
'url' => $item['loc'],
];
}
return $item;
};
add_filter( 'rank_math/sitemap/index/entry', $capture, 10, 3 );
$provider->get_index_links( $max_entries );
remove_filter( 'rank_math/sitemap/index/entry', $capture, 10 );
$post_type_totals = [];
$page_numbers = [];
$sitemaps = [];
foreach ( $entries as $entry ) {
$type = $entry['type'];
$page_numbers[ $type ] = ( $page_numbers[ $type ] ?? 0 ) + 1;
$page = $page_numbers[ $type ];
if ( $provider instanceof Post_Type_Provider ) {
if ( ! isset( $post_type_totals[ $type ] ) ) {
$post_type_totals[ $type ] = (int) $provider->get_post_type_count( $type );
}
$offset = ( $page - 1 ) * $max_entries;
$estimated_count = max( 0, min( $max_entries, $post_type_totals[ $type ] - $offset ) );
} elseif ( $provider instanceof Taxonomy_Provider ) {
$estimated_count = $this->count_taxonomy_page( $provider, $type, $max_entries, $page );
} elseif ( $provider instanceof Author_Provider ) {
$estimated_count = count(
(array) $provider->get_users(
[
'offset' => ( $page - 1 ) * $max_entries,
'number' => $max_entries,
]
)
);
} else {
$estimated_count = $max_entries;
}
$sitemaps[] = [
'type' => $type,
'url' => $entry['url'],
'estimated_count' => $estimated_count,
];
}
return $sitemaps;
}
/**
* Build the Local SEO sitemap entry, if the Local Sitemap is active.
*
* Mirrors the conditions in RankMath\Local_Seo\Local_Seo::location_sitemap(),
* which is what actually decides whether local-sitemap.xml gets served.
*
* @return array|null
*/
private function get_local_sitemap(): ?array {
if (
! Helper::is_module_active( 'sitemap' ) ||
! Helper::is_module_active( 'local-seo' ) ||
'company' !== Helper::get_settings( 'titles.knowledgegraph_type' ) ||
! apply_filters( 'rank_math/sitemap/locations', false ) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
) {
return null;
}
$locations = apply_filters( // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
'rank_math/sitemap/locations/data',
[ [ 'name' => Helper::get_settings( 'titles.knowledgegraph_name' ) ] ]
);
return [
'type' => 'local',
'url' => Router::get_base_url( 'local-sitemap.xml' ),
'estimated_count' => is_array( $locations ) ? count( $locations ) : 0,
];
}
/**
* Real per-page term count for a taxonomy, via Taxonomy_Provider::get_terms().
*
* @param Taxonomy_Provider $provider Taxonomy provider instance.
* @param string $taxonomy Taxonomy slug.
* @param int $max_entries Entries per sitemap page.
* @param int $current_page Page number (1-indexed).
* @return int
*/
private function count_taxonomy_page( Taxonomy_Provider $provider, string $taxonomy, int $max_entries, int $current_page ): int {
$taxonomy_object = get_taxonomy( $taxonomy );
if ( ! $taxonomy_object ) {
return 0;
}
return count( (array) $provider->get_terms( $taxonomy_object, $max_entries, $current_page ) );
}
/**
* JSON schema for the ability output.
*
* @return array
*/
private function output_schema(): array {
return [
'type' => 'object',
'properties' => [
'enabled' => [
'type' => 'boolean',
'description' => esc_html__( 'Whether the XML sitemap module is active.', 'seo-by-rank-math' ),
],
'index_url' => [
'type' => 'string',
'description' => esc_html__( 'The URL of the sitemap index file.', 'seo-by-rank-math' ),
],
'sitemaps' => [
'type' => 'array',
'description' => esc_html__( 'The active sitemap types, e.g. post types, taxonomies, and the Local SEO sitemap (PRO adds news/video when active).', 'seo-by-rank-math' ),
'items' => [
'type' => 'object',
'properties' => [
'type' => [ 'type' => 'string' ],
'url' => [ 'type' => 'string' ],
'estimated_count' => [ 'type' => 'integer' ],
],
],
],
],
];
}
}
@@ -0,0 +1,79 @@
<?php
/**
* Subscriber for Sitemap abilities.
*
* @since 1.0.277
* @package RankMath
* @subpackage RankMath\Abilities\Sitemap
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Abilities\Sitemap;
use RankMath\Traits\Hooker;
use RankMath\Abilities\Subscriber_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Registers the Sitemap ability category and its abilities.
*/
class Subscriber implements Subscriber_Interface {
use Hooker;
/**
* Ability category slug for Sitemap abilities.
*/
const CATEGORY_SLUG = 'rank-math-sitemap';
/**
* Shared meta args.
*
* @var array
*/
private $shared_meta;
/**
* Constructor.
*
* @param array $shared_meta Shared meta args from the top-level Abilities class.
*/
public function __construct( array $shared_meta ) {
$this->shared_meta = $shared_meta;
}
/**
* Wire hooks.
*
* @return void
*/
public function register(): void {
$this->action( 'wp_abilities_api_categories_init', 'register_category' );
$this->action( 'wp_abilities_api_init', 'register_get_sitemap_status' );
}
/**
* Register the Sitemap ability category.
*
* @return void
*/
public function register_category(): void {
\wp_register_ability_category(
self::CATEGORY_SLUG,
[
'label' => esc_html__( 'Sitemap', 'seo-by-rank-math' ),
'description' => esc_html__( 'Abilities to inspect the XML sitemap status.', 'seo-by-rank-math' ),
]
);
}
/**
* Register the rank-math/get-sitemap-status ability.
*
* @return void
*/
public function register_get_sitemap_status(): void {
( new Get_Sitemap_Status( self::CATEGORY_SLUG, $this->shared_meta ) )->register();
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,487 @@
<?php
/**
* Admin bar menu.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Core
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath;
use RankMath\Paper\Paper;
use RankMath\Traits\Ajax;
use RankMath\Traits\Meta;
use RankMath\Traits\Hooker;
use RankMath\Helpers\Arr;
use RankMath\Helpers\Url;
use RankMath\Helpers\Param;
use RankMath\Rest\Rest_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Admin_Bar_Menu class.
*/
class Admin_Bar_Menu {
use Hooker;
use Ajax;
use Meta;
/**
* The unique identifier used for the menu.
*
* @var string
*/
const MENU_IDENTIFIER = 'rank-math';
/**
* Hold menu items.
*
* @var array
*/
private $items = [];
/**
* Constructor method.
*/
public function __construct() {
$this->ajax( 'mark_page_as', 'mark_page_as' );
$this->action( 'admin_bar_menu', 'add_menu', 100 );
}
/**
* AJAX function to mark page as Pillar Content/Noindex/Nofollow.
*/
public function mark_page_as() {
check_ajax_referer( 'rank-math-ajax-nonce', 'security' );
$this->has_cap_ajax( 'onpage_general' );
$what = Param::post( 'what', '', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK );
$object_id = Param::post( 'objectID', 0, FILTER_VALIDATE_INT );
$object_type = Param::post( 'objectType', '', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK );
if ( ! $what || ! $object_id || ! $object_type ) {
return 0;
}
if ( ! in_array( $object_type, [ 'post', 'term', 'user' ], true ) || ! Rest_Helper::can_edit_object( $object_type, $object_id ) ) {
return 0;
}
if ( 'pillar_content' === $what ) {
$current = $this->get_meta( $object_type, $object_id, 'rank_math_pillar_content' );
$updated = 'on' === $current ? 'off' : 'on';
$this->update_meta( $object_type, $object_id, 'rank_math_pillar_content', $updated );
die( '1' );
}
if ( 'noindex' === $what || 'nofollow' === $what ) {
$robots = (array) $this->get_meta( $object_type, $object_id, 'rank_math_robots' );
$robots = array_filter( $robots );
Arr::add_delete_value( $robots, $what );
$robots = $this->normalize_robots( $what, array_unique( $robots ) );
$this->update_meta( $object_type, $object_id, 'rank_math_robots', $robots );
if ( 'noindex' === $what ) {
$this->do_action( 'sitemap/invalidate_object_type', $object_type, $object_id );
}
die( '1' );
}
die();
}
/**
* Add SEO item to admin bar with context-specific submenu items.
*
* @param WP_Admin_Bar $wp_admin_bar Admin bar instance to add the menu to.
*/
public function add_menu( $wp_admin_bar ) {
if ( ! $this->can_add_menu() ) {
return;
}
$this->add_root_menu();
if ( Helper::has_cap( 'titles' ) ) {
$this->add_page_menu();
}
if ( $this->is_front() ) {
$this->add_seo_tools();
}
if ( $this->can_add_mark_menu() ) {
$this->add_mark_page_menu();
}
/**
* Add item to rank math admin bar node.
*
* @param Admin_Bar_Menu $this Class instance.
*/
$this->do_action( 'admin_bar/items', $this );
$this->add_order();
uasort( $this->items, [ $this, 'sort_by_priority' ] );
array_walk( $this->items, [ $wp_admin_bar, 'add_node' ] );
}
/**
* Normalize robots.
*
* @param string $what Current admin menu process.
* @param array $robots Array to normalize.
*
* @return array
*/
private function normalize_robots( $what, $robots ) {
if ( 'noindex' !== $what ) {
return $robots;
}
if ( ! in_array( 'noindex', $robots, true ) ) {
$robots[] = ! in_array( 'index', $robots, true ) ? 'index' : '';
return $robots;
}
if ( false !== ( $key = array_search( 'index', $robots ) ) ) { // @codingStandardsIgnoreLine
unset( $robots[ $key ] );
}
return $robots;
}
/**
* Keep original order when uasort() deals with equal "priority" values.
*/
private function add_order() {
$order = 0;
foreach ( $this->items as &$item ) {
$item['order'] = $order++;
}
}
/**
* Add root menu.
*/
private function add_root_menu() {
$first_menu = get_transient( 'rank_math_first_submenu_id' );
$first_menu = $first_menu && 'rank-math' !== $first_menu ? str_replace( 'rank-math-', '', $first_menu ) : '';
$this->items['main'] = [
'id' => self::MENU_IDENTIFIER,
'title' => '<span class="rank-math-icon">' . $this->get_icon() . '</span><span class="rank-math-text">' . esc_html__( 'Rank Math SEO', 'seo-by-rank-math' ) . '</span>',
'href' => Helper::get_admin_url( $first_menu ),
'meta' => [ 'title' => esc_html__( 'Rank Math Dashboard', 'seo-by-rank-math' ) ],
'priority' => 10,
];
if ( current_user_can( 'manage_options' ) ) {
$this->add_sub_menu(
'dashboard',
[
'title' => esc_html__( 'Dashboard', 'seo-by-rank-math' ),
'href' => $this->items['main']['href'],
'meta' => [ 'title' => esc_html__( 'Dashboard', 'seo-by-rank-math' ) ],
'priority' => 20,
]
);
}
}
/**
* Add page menu.
*/
private function add_page_menu() {
$hash = [
'add_home_menu' => is_front_page(),
'add_post_type_menu' => is_singular( Helper::get_accessible_post_types() ) || is_home(),
'add_date_menu' => is_date(),
'add_taxonomy_menu' => is_archive() && ! is_post_type_archive() && ! is_author(),
'add_search_menu' => is_search(),
];
foreach ( $hash as $func => $can_run ) {
if ( true === $can_run ) {
$this->$func();
break;
}
}
}
/**
* Add homepage menu
*/
private function add_home_menu() {
$this->add_sub_menu(
'home',
[
'title' => esc_html__( 'Homepage SEO', 'seo-by-rank-math' ),
'href' => Helper::get_settings_url( 'titles', 'homepage' ),
'meta' => [ 'title' => esc_html__( 'Edit Homepage SEO Settings', 'seo-by-rank-math' ) ],
'priority' => 35,
]
);
}
/**
* Add post_type menu
*/
private function add_post_type_menu() {
$post_type = get_post_type();
if ( ! $post_type ) {
return;
}
$name = get_post_type_object( $post_type )->labels->name;
if ( is_home() ) {
$post_type = 'page';
$name = esc_html__( 'Pages', 'seo-by-rank-math' );
}
$this->add_sub_menu(
'posttype',
[
/* translators: Post Type Singular Name */
'title' => sprintf( esc_html__( 'SEO Settings for %s', 'seo-by-rank-math' ), $name ),
'href' => Helper::get_settings_url( 'titles', 'post-type-' . $post_type ),
'meta' => [ 'title' => esc_html__( 'Edit default SEO settings for this post type', 'seo-by-rank-math' ) ],
'priority' => 35,
]
);
}
/**
* Add taxonomy menu
*/
private function add_taxonomy_menu() {
$term = get_queried_object();
if ( empty( $term ) || ! ( $term instanceof \WP_Term ) ) {
return;
}
$labels = get_taxonomy_labels( get_taxonomy( $term->taxonomy ) );
$this->add_sub_menu(
'tax',
[
/* translators: Taxonomy Singular Name */
'title' => sprintf( esc_html__( 'SEO Settings for %s', 'seo-by-rank-math' ), $labels->name ),
'href' => Helper::get_settings_url( 'titles', 'taxonomy-' . $term->taxonomy ),
'meta' => [ 'title' => esc_html__( 'Edit SEO settings for this archive page', 'seo-by-rank-math' ) ],
'priority' => 35,
]
);
}
/**
* Add date archive menu
*/
private function add_date_menu() {
$this->add_sub_menu(
'date',
[
'title' => esc_html__( 'SEO Settings for Date Archives', 'seo-by-rank-math' ),
'href' => Helper::get_settings_url( 'titles', 'global' ),
'meta' => [ 'title' => esc_html__( 'Edit SEO settings for this archive page', 'seo-by-rank-math' ) ],
'priority' => 35,
]
);
}
/**
* Add search result menu
*/
private function add_search_menu() {
$this->add_sub_menu(
'search',
[
'title' => esc_html__( 'SEO Settings for Search Page', 'seo-by-rank-math' ),
'href' => Helper::get_settings_url( 'titles', 'global' ),
'meta' => [ 'title' => esc_html__( 'Edit SEO settings for the search results page', 'seo-by-rank-math' ) ],
'priority' => 35,
]
);
}
/**
* Add mark page menu.
*/
private function add_mark_page_menu() {
$this->add_sub_menu(
'mark-me',
[
'title' => esc_html__( 'Mark this page', 'seo-by-rank-math' ),
'href' => '#',
'priority' => 100,
]
);
$is_pillar_content = '';
$dashicon_format = '<span class="dashicons dashicons-%s rm-mark-page-icon"></span>';
if ( is_singular( Helper::get_accessible_post_types() ) ) {
if ( get_post_meta( get_the_ID(), 'rank_math_pillar_content', true ) === 'on' ) {
$is_pillar_content = sprintf( $dashicon_format, 'yes' );
}
$this->add_sub_menu(
'pillar-content',
[
'title' => $is_pillar_content . esc_html__( 'As Pillar Content', 'seo-by-rank-math' ),
'href' => '#pillar_content',
'meta' => [ 'class' => 'mark-page-as' ],
],
'mark-me'
);
}
if ( Paper::get() ) {
$robots = Paper::get()->get_robots();
$noindex_check = in_array( 'noindex', $robots, true ) ? sprintf( $dashicon_format, 'yes' ) : '';
$this->add_sub_menu(
'no-index',
[
'title' => $noindex_check . esc_html__( 'As NoIndex', 'seo-by-rank-math' ),
'href' => '#noindex',
'meta' => [ 'class' => 'mark-page-as' ],
],
'mark-me'
);
$nofollow_check = in_array( 'nofollow', $robots, true ) ? sprintf( $dashicon_format, 'yes' ) : '';
$this->add_sub_menu(
'no-follow',
[
'title' => $nofollow_check . esc_html__( 'As NoFollow', 'seo-by-rank-math' ),
'href' => '#nofollow',
'meta' => [ 'class' => 'mark-page-as' ],
],
'mark-me'
);
}
}
/**
* Third party SEO Tools, like the Google Structured Data Testing Tool.
*/
private function add_seo_tools() {
$this->add_sub_menu(
'third-party',
[
'title' => esc_html__( 'External Tools', 'seo-by-rank-math' ),
'href' => '#',
'priority' => 200,
]
);
$url = rawurlencode( Url::get_current_url() );
$items = [
'google-pagespeed' => [
'title' => esc_html__( 'Google PageSpeed', 'seo-by-rank-math' ),
'href' => 'https://developers.google.com/speed/pagespeed/insights/?url=' . $url,
'meta' => [ 'title' => esc_html__( 'Google PageSpeed Insights', 'seo-by-rank-math' ) ],
],
'google-richresults-mobile' => [
'title' => esc_html__( 'Google Rich Results (Mobile)', 'seo-by-rank-math' ),
'href' => 'https://search.google.com/test/rich-results?url=' . $url . '&user_agent=1',
'meta' => [ 'title' => esc_html__( 'Google Rich Results Test - Googlebot Smartphone', 'seo-by-rank-math' ) ],
],
'google-richresults-desktop' => [
'title' => esc_html__( 'Google Rich Results (Desktop)', 'seo-by-rank-math' ),
'href' => 'https://search.google.com/test/rich-results?url=' . $url . '&user_agent=2',
'meta' => [ 'title' => esc_html__( 'Google Rich Results Test - Googlebot Desktop', 'seo-by-rank-math' ) ],
],
'fb-debugger' => [
'title' => esc_html__( 'Facebook Debugger', 'seo-by-rank-math' ),
'href' => 'https://developers.facebook.com/tools/debug/sharing/?q=' . $url,
'meta' => [ 'title' => esc_html__( 'Facebook Sharing Debugger', 'seo-by-rank-math' ) ],
],
];
foreach ( $items as $id => $args ) {
$args['meta']['target'] = '_blank';
$this->add_sub_menu( $id, $args, 'third-party' );
}
}
/**
* Add sub menu item
*
* @param string $id Unique ID for the node.
* @param array $args Arguments for adding a node.
* @param string $parent_node Node parent.
*/
public function add_sub_menu( $id, $args, $parent_node = '' ) {
$args['priority'] = isset( $args['priority'] ) ? $args['priority'] : 999;
$args['id'] = 'rank-math-' . $id;
$args['parent'] = '' !== $parent_node ? 'rank-math-' . $parent_node : self::MENU_IDENTIFIER;
$this->items[ $id ] = $args;
}
/**
* Can current user has capability for admin menu.
*
* @return bool
*/
private function can_add_menu() {
return Helper::has_cap( 'admin_bar' );
}
/**
* Can add mark me menu.
*
* @return bool
*/
private function can_add_mark_menu() {
return $this->is_front() && Helper::has_cap( 'onpage_general' );
}
/**
* Is frontend.
*
* @return bool
*/
private function is_front() {
return ! is_admin() && ! is_preview();
}
/**
* Sort admin bar items callback.
*
* @param array $item1 Item A to compare.
* @param array $item2 Item B to compare.
*
* @return integer
*/
private function sort_by_priority( $item1, $item2 ) {
if ( $item1['priority'] === $item2['priority'] ) {
return $item1['order'] < $item2['order'] ? -1 : 1;
}
return $item1['priority'] < $item2['priority'] ? -1 : 1;
}
/**
* Get Rank Math icon.
*
* @param integer $width Width of the icon.
*
* @return string
*/
private function get_icon( $width = 20 ) {
return '<svg viewBox="0 0 462.03 462.03" xmlns="http://www.w3.org/2000/svg" width="' . $width . '"><g><path d="m462 234.84-76.17 3.43 13.43 21-127 81.18-126-52.93-146.26 60.97 10.14 24.34 136.1-56.71 128.57 54 138.69-88.61 13.43 21z"/><path d="m54.1 312.78 92.18-38.41 4.49 1.89v-54.58h-96.67zm210.9-223.57v235.05l7.26 3 89.43-57.05v-181zm-105.44 190.79 96.67 40.62v-165.19h-96.67z"/></g></svg>';
}
}
@@ -0,0 +1,52 @@
<?php
/**
* Breadcrumbs for the Rank Math pages.
*
* @since 1.0.44
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Helper;
use RankMath\Helpers\Param;
use RankMath\Google\Console;
defined( 'ABSPATH' ) || exit;
/**
* Admin Header class.
*
* @codeCoverageIgnore
*/
class Admin_Breadcrumbs {
/**
* Display Header.
*/
public function display() {
?>
<div class="rank-math-breadcrumbs-wrap">
<div class="rank-math-breadcrumbs">
<span><?php echo esc_html__( 'Dashboard', 'seo-by-rank-math' ); ?></span>
<span class="divider">/</span>
<span class="active"><?php echo esc_html( $this->get_page_title() ); ?></span>
</div>
</div>
<?php
}
/**
* Get Current Admin Page Title.
*/
private function get_page_title() {
$base = __( 'Modules', 'seo-by-rank-math' );
if ( is_network_admin() ) {
$base = __( 'Help', 'seo-by-rank-math' );
}
$default = 'rank-math' === Param::get( 'page' ) ? $base : get_admin_page_title();
return str_replace( '_', ' ', Param::get( 'view', $default, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK ) );
}
}
@@ -0,0 +1,135 @@
<?php
/**
* The nav tabs on the Dashboard page.
*
* @since 1.0.40
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Helper;
use RankMath\Helpers\Security;
use RankMath\Helpers\Param;
defined( 'ABSPATH' ) || exit;
/**
* Admin Dashboard Nav class.
*
* @codeCoverageIgnore
*/
class Admin_Dashboard_Nav {
/**
* Display dashboard tabs.
*/
public function display() {
$nav_links = $this->get_nav_links();
if ( empty( $nav_links ) ) {
return;
}
?>
<div class="rank-math-tab-nav" role="tablist" aria-orientation="horizontal">
<?php
foreach ( $nav_links as $id => $link ) {
$this->nav_link( $link );
}
?>
</div>
<?php
}
/**
* Get URL for dashboard nav links.
*
* @param array $link Link data.
* @return string Link URL.
*/
public function get_link_url( $link ) {
return is_network_admin() ?
Security::add_query_arg(
[
'page' => 'rank-math',
'view' => $link['id'],
],
network_admin_url( 'admin.php' )
) :
Helper::get_admin_url( $link['url'], $link['args'] );
}
/**
* Output dashboard nav link.
*
* @param array $link Link data.
* @return void
*/
public function nav_link( $link ) {
if ( isset( $link['cap'] ) && ! current_user_can( $link['cap'] ) ) {
return;
}
$default_tab = is_network_admin() ? 'help' : 'modules';
?>
<a
class="rank-math-tab<?php echo Param::get( 'view', $default_tab ) === sanitize_html_class( $link['id'] ) ? ' is-active' : ''; ?>"
href="<?php echo esc_url( $this->get_link_url( $link ) ); ?>"
title="<?php echo esc_attr( $link['title'] ); ?>">
<?php echo esc_html( $link['title'] ); ?>
</a>
<?php
}
/**
* Get dashboard navigation links
*
* @return array
*/
private function get_nav_links() {
$links = [
'modules' => [
'id' => 'modules',
'url' => '',
'args' => 'view=modules',
'cap' => 'manage_options',
'title' => esc_html__( 'Modules', 'seo-by-rank-math' ),
],
'help' => [
'id' => 'help',
'url' => '',
'args' => 'view=help',
'cap' => 'manage_options',
'title' => esc_html__( 'Help', 'seo-by-rank-math' ),
],
'wizard' => [
'id' => 'wizard',
'url' => 'wizard',
'args' => '',
'cap' => 'manage_options',
'title' => esc_html__( 'Setup Wizard', 'seo-by-rank-math' ),
],
];
if ( Helper::is_advanced_mode() ) {
$links['import-export'] = [
'id' => 'import-export',
'url' => 'status',
'args' => 'view=import_export',
'cap' => 'install_plugins',
'title' => esc_html__( 'Import &amp; Export', 'seo-by-rank-math' ),
];
}
if ( Helper::is_plugin_active_for_network() ) {
unset( $links['help'] );
}
if ( is_network_admin() ) {
$links = [];
}
return apply_filters( 'rank_math/admin/dashboard_nav_links', $links );
}
}
@@ -0,0 +1,157 @@
<?php
/**
* Header for the Rank Math pages
*
* @since 1.0.44
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Helper;
use RankMath\KB;
use RankMath\Helpers\Param;
defined( 'ABSPATH' ) || exit;
/**
* Admin Header class.
*
* @codeCoverageIgnore
*/
class Admin_Header {
/**
* Hold current screen ID.
*
* @var Current screen ID.
*/
private $screen_id = '';
/**
* Display Header.
*
* @param bool $show_breadcrumbs Determines whether to show breadcrumbs or not.
*/
public function display( $show_breadcrumbs ) {
$logo_url = '<a href="' . esc_url( Helper::get_admin_url() ) . '"><i class="rm-icon rm-icon-rank-math"></i></a>';
$this->screen_id = $this->get_current_screen();
?>
<div class="rank-math-header">
<div class="rank-math-logo">
<?php echo $logo_url; // phpcs:ignore ?>
</div>
<h1 class="rank-math-logo-text">
Rank Math SEO
<?php do_action( 'rank_math/pro_badge' ); ?>
</h1>
<?php $this->get_search_options(); ?>
<?php $this->get_mode_selector(); ?>
<?php do_action( 'rank_math/before_help_link' ); ?>
<a href="<?php echo esc_url( $this->get_help_link() ); ?>" title="<?php esc_attr_e( 'Rank Math Knowledge Base', 'seo-by-rank-math' ); ?>" target="_blank" class="button rank-math-help"><i class="dashicons dashicons-editor-help"></i></a>
</div>
<?php
// Breadcrumbs.
if ( $show_breadcrumbs ) {
rank_math()->admin->display_admin_breadcrumbs();
}
}
/**
* Get Search Options.
*/
private function get_search_options() {
if (
! in_array(
$this->screen_id,
[
'rank-math_page_rank-math-options-general',
'rank-math_page_rank-math-options-titles',
'rank-math_page_rank-math-options-sitemap',
],
true
)
) {
return;
}
?>
<div class="rank-math-search-options">
<div class="components-input-control">
<div class="components-input-control__container">
<!-- <i class="rm-icon rm-icon-search"></i> -->
<input type="search" class="components-input-control__input" value="" placeholder="<?php esc_attr_e( 'Search Options', 'seo-by-rank-math' ); ?>" style="width: 100%;">
<!-- <em class="clear-search dashicons dashicons-no-alt"></em> -->
</div>
</div>
</div>
<?php
}
/**
* Get Mode Selector.
*/
private function get_mode_selector() {
if (
! in_array(
$this->screen_id,
[
'toplevel_page_rank-math',
'rank-math_page_rank-math-status',
],
true
)
) {
return;
}
$is_advanced_mode = Helper::is_advanced_mode();
?>
<div class="rank-math-mode-selector">
<a href="#" class="<?php echo ! $is_advanced_mode ? 'active' : ''; ?>" data-mode="easy"><?php esc_attr_e( 'Easy Mode', 'seo-by-rank-math' ); ?></a>
<a href="#" class="<?php echo $is_advanced_mode ? 'active' : ''; ?>" data-mode="advanced"><?php esc_attr_e( 'Advanced Mode', 'seo-by-rank-math' ); ?></a>
</div>
<?php
}
/**
* Get Current Screen ID.
*/
private function get_help_link() {
$links = [
'import-export-settings' => 'import_export' === Param::get( 'view' ),
'version-control' => 'version_control' === Param::get( 'view' ) || 'rank-math-status' === Param::get( 'page' ),
'general-settings' => 'rank-math-options-general' === Param::get( 'page' ),
'titles-meta' => 'rank-math-options-titles' === Param::get( 'page' ),
'sitemap-general' => 'rank-math-options-sitemap' === Param::get( 'page' ),
'role-manager' => 'rank-math-role-manager' === Param::get( 'page' ),
'seo-analysis' => 'rank-math-seo-analysis' === Param::get( 'page' ),
'content-ai-restore-credits' => 'rank-math-content-ai-page' === Param::get( 'page' ),
];
$link = KB::get( 'knowledgebase', 'RM Header KB Icon' );
foreach ( $links as $key => $value ) {
if ( $value ) {
$link = KB::get( $key, 'Admin Bar ' . ucwords( str_replace( '-', ' ', $key ) ) );
break;
}
}
return $link;
}
/**
* Get Current Screen ID.
*/
private function get_current_screen() {
$screen = get_current_screen();
if ( empty( $screen ) ) {
return '';
}
return $screen->id;
}
}
@@ -0,0 +1,434 @@
<?php
/**
* Admin helper Functions.
*
* This file contains functions needed on the admin screens.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\KB;
use RankMath\Helper;
use RankMath\Data_Encryption;
use RankMath\Helpers\Security;
use RankMath\Helpers\Param;
defined( 'ABSPATH' ) || exit;
/**
* Admin_Helper class.
*/
class Admin_Helper {
/**
* Get .htaccess related data.
*
* @return array
*/
public static function get_htaccess_data() {
if ( ! Helper::is_filesystem_direct() ) {
return [
'content' => '',
'writable' => false,
];
}
$wp_filesystem = Helper::get_filesystem();
if ( empty( $wp_filesystem ) ) {
return;
}
$htaccess_file = get_home_path() . '.htaccess';
return ! $wp_filesystem->exists( $htaccess_file ) ? false : [
'content' => $wp_filesystem->get_contents( $htaccess_file ),
'writable' => $wp_filesystem->is_writable( $htaccess_file ),
];
}
/**
* Get tooltip HTML.
*
* @param string $message Message to show in tooltip.
*
* @return string
*/
public static function get_tooltip( $message ) {
return '<span class="rank-math-tooltip"><em class="dashicons-before dashicons-editor-help"></em><span>' . $message . '</span></span>';
}
/**
* Get admin view file.
*
* @param string $view View filename.
*
* @return string Complete path to view
*/
public static function get_view( $view ) {
$view = sanitize_key( $view );
$view = rank_math()->admin_dir() . "views/{$view}.php";
if ( ! file_exists( $view ) ) {
Helper::redirect( Helper::get_admin_url() );
exit;
}
return $view;
}
/**
* Get taxonomies as choices.
*
* @param array $args (Optional) Arguments passed to filter list.
*
* @return array|bool
*/
public static function get_taxonomies_options( $args = [] ) {
global $wp_taxonomies;
$args = wp_parse_args( $args, [ 'public' => true ] );
$taxonomies = wp_filter_object_list( $wp_taxonomies, $args, 'and', 'label' );
return empty( $taxonomies ) ? false : [ 'off' => esc_html__( 'None', 'seo-by-rank-math' ) ] + $taxonomies;
}
/**
* Registration data get/update.
*
* @param array|bool|null $data Array of data to save.
*
* @return array
*/
public static function get_registration_data( $data = null ) {
$row = 'rank_math_connect_data';
$keys = [
'username',
'email',
'api_key',
'plan',
];
// Setter.
if ( ! is_null( $data ) ) {
if ( false === $data ) {
update_option( 'rank_math_registration_skip', 1 );
return delete_option( $row );
}
foreach ( $keys as $key ) {
if ( isset( $data[ $key ] ) ) {
$data[ $key ] = Data_Encryption::encrypt( $data[ $key ] );
}
}
Helper::remove_notification( 'rank-math-site-url-mismatch' );
update_option( 'rank_math_registration_skip', 1 );
$connected = update_option( $row, $data );
do_action( 'rank_math/connect/account_connected', $data );
return $connected;
}
// Getter.
$options = Helper::is_plugin_active_for_network() ? get_blog_option( get_main_site_id(), $row, false ) : get_option( $row, false );
if ( empty( $options ) ) {
return false;
}
foreach ( $keys as $key ) {
if ( isset( $options[ $key ] ) ) {
$options[ $key ] = Data_Encryption::decrypt( $options[ $key ] );
}
}
if ( ! self::is_valid_registration( $options ) ) {
// Delete invalid registration data.
delete_option( $row );
// Ask the user to reconnect.
Helper::add_notification(
__( 'Unable to validate Rank Math SEO registration data.', 'seo-by-rank-math' ) .
' <a href="' . esc_url( self::get_activate_url() ) . '">' . __( 'Please try reconnecting.', 'seo-by-rank-math' ) . '</a> ' .
sprintf(
/* translators: KB Link */
__( 'If the issue persists, please try the solution described in our Knowledge Base article: %s', 'seo-by-rank-math' ),
'<a href="' . KB::get( 'unable-to-encrypt', 'Registration Data' ) . '" target="_blank">' . __( '[3. Unable to Encrypt]', 'seo-by-rank-math' ) . '</a>'
),
[ 'type' => 'error' ]
);
return false;
}
/**
* Filter whether we need to check for URL mismatch or not.
*/
$do_url_check = apply_filters( 'rank_math/registration/do_url_check', ! get_option( 'rank_math_siteurl_mismatch_notice_dismissed' ) );
if ( $do_url_check && isset( $options['site_url'] ) && Helper::get_home_url() !== $options['site_url'] ) {
$message = esc_html__( 'Seems like your site URL has changed since you connected to Rank Math.', 'seo-by-rank-math' ) . ' <a href="' . self::get_activate_url() . '">' . esc_html__( 'Click here to reconnect.', 'seo-by-rank-math' ) . '</a>';
Helper::add_notification(
$message,
[
'type' => 'warning',
'id' => 'rank-math-site-url-mismatch',
]
);
}
/**
* Ensure the site_url is returned if it is absent, as it is required for the Content AI.
*/
if ( empty( $options['site_url'] ) ) {
$options['site_url'] = Helper::get_home_url();
}
return $options;
}
/**
* Check if registration data is valid.
*
* @param array $data Registration data.
*
* @return bool
*/
public static function is_valid_registration( $data ) {
if ( empty( $data['username'] ) || empty( $data['email'] ) || empty( $data['api_key'] ) || empty( $data['plan'] ) ) {
return false;
}
if ( ! filter_var( $data['email'], FILTER_VALIDATE_EMAIL ) ) {
return false;
}
if ( strlen( $data['plan'] ) > 32 ) { // This can happen when the decryption fails for some reason.
return false;
}
return true;
}
/**
* Get user plan.
*/
public static function get_user_plan() {
$data = self::get_registration_data();
return $data['plan'];
}
/**
* Is user plan expired.
*
* @return boolean
*/
public static function is_plan_expired() {
$data = self::get_registration_data();
if ( ! isset( $data['plan'] ) ) {
return true;
}
return 'free' === $data['plan'];
}
/**
* Remove registration data and disconnect from RankMath.com.
*/
public static function deregister_user() {
$registered = self::get_registration_data();
if ( $registered && isset( $registered['username'] ) && isset( $registered['api_key'] ) ) {
Api::get()->deactivate_site( $registered['username'], $registered['api_key'] );
self::get_registration_data( false );
do_action( 'rank_math/deregister_site' );
}
}
/**
* Check if current page is media list page.
*
* @return bool
*/
public static function is_media_library() {
global $pagenow;
return 'upload.php' === $pagenow;
}
/**
* Check if current page is post list page.
*
* @return bool
*/
public static function is_post_list() {
global $pagenow;
return 'edit.php' === $pagenow;
}
/**
* Check if current page is post create/edit screen.
*
* @return bool
*/
public static function is_post_edit() {
global $pagenow;
return ! Helper::is_ux_builder() && ( 'post.php' === $pagenow || 'post-new.php' === $pagenow );
}
/**
* Check if current page is term create/edit screen.
*
* @return bool
*/
public static function is_term_edit() {
global $pagenow;
return 'term.php' === $pagenow || 'edit-tags.php' === $pagenow;
}
/**
* Check if current page is term create/term listing.
*
* @return bool
*/
public static function is_term_listing() {
global $pagenow;
return 'edit-tags.php' === $pagenow;
}
/**
* Check if current page is user create/edit screen.
*
* @return bool
*/
public static function is_user_edit() {
global $pagenow;
return 'profile.php' === $pagenow || 'user-edit.php' === $pagenow;
}
/**
* Check if current page is user or term create/edit screen.
*
* @return bool
*/
public static function is_term_profile_page() {
global $pagenow;
return self::is_term_edit() || self::is_user_edit();
}
/**
* Get product activation URL.
*
* @param string $redirect_to Redirecto url.
*
* @return string Activate URL.
*/
public static function get_activate_url( $redirect_to = null ) {
if ( empty( $redirect_to ) ) {
$redirect_to = Security::add_query_arg_raw(
[
'page' => 'rank-math',
'view' => 'help',
'nonce' => wp_create_nonce( 'rank_math_register_product' ),
],
( is_multisite() && is_plugin_active_for_network( plugin_basename( RANK_MATH_FILE ) ) ) ? network_admin_url( 'admin.php' ) : admin_url( 'admin.php' )
);
} else {
$redirect_to = Security::add_query_arg_raw(
[
'nonce' => wp_create_nonce( 'rank_math_register_product' ),
],
$redirect_to
);
}
$args = [
'site' => rawurlencode( home_url() ),
'r' => rawurlencode( $redirect_to ),
];
return apply_filters(
'rank_math/license/activate_url',
Security::add_query_arg_raw( $args, RANK_MATH_SITE_URL . '/auth' ),
$args
);
}
/**
* Check if page is set as Homepage.
*
* @since 1.0.42
*
* @return boolean
*/
public static function is_home_page() {
$front_page = (int) get_option( 'page_on_front' );
if ( Helper::is_divi_frontend_editor() ) {
$p = get_post();
return ! empty( $p->ID ) && $p->ID === $front_page;
}
return $front_page && self::is_post_edit() && (int) Param::get( 'post' ) === $front_page;
}
/**
* Check if page is set as Posts Page.
*
* @since 1.0.43
*
* @return boolean
*/
public static function is_posts_page() {
$posts_page = (int) get_option( 'page_for_posts' );
return $posts_page && self::is_post_edit() && (int) Param::get( 'post' ) === $posts_page;
}
/**
* Get Trends icon <svg> element.
*
* @return string
*/
public static function get_trends_icon_svg() {
return '<svg viewBox="0 0 610 610"><path d="M18.85,446,174.32,290.48l58.08,58.08L76.93,504a14.54,14.54,0,0,1-20.55,0L18.83,466.48a14.54,14.54,0,0,1,0-20.55Z" style="fill:#4285f4"/><path d="M242.65,242.66,377.59,377.6l-47.75,47.75a14.54,14.54,0,0,1-20.55,0L174.37,290.43l47.75-47.75A14.52,14.52,0,0,1,242.65,242.66Z" style="fill:#ea4335"/><polygon points="319.53 319.53 479.26 159.8 537.34 217.88 377.61 377.62 319.53 319.53" style="fill:#fabb05"/><path d="M594.26,262.73V118.61h0a16.94,16.94,0,0,0-16.94-16.94H433.2a16.94,16.94,0,0,0-12,28.92L565.34,274.71h0a16.94,16.94,0,0,0,28.92-12Z" style="fill:#34a853"/><rect width="610" height="610" style="fill:none"/></svg>';
}
/**
* Check if siteurl & home options are both valid URLs.
*
* @return boolean
*/
public static function is_site_url_valid() {
return (bool) filter_var( get_option( 'siteurl' ), FILTER_VALIDATE_URL ) && (bool) filter_var( get_option( 'home' ), FILTER_VALIDATE_URL );
}
/**
* Maybe show notice about invalid siteurl.
*/
public static function maybe_show_invalid_siteurl_notice() {
if ( ! self::is_site_url_valid() ) {
?>
<p class="notice notice-warning notice-alt notice-connect-disabled">
<?php
printf(
// Translators: 1 is "WordPress Address (URL)", 2 is "Site Address (URL)", 3 is a link to the General Settings, with "WordPress General Settings" as anchor text.
esc_html__( 'Rank Math cannot be connected because your site URL doesn\'t appear to be a valid URL. If the domain name contains special characters, please make sure to use the encoded version in the %1$s &amp; %2$s fields on the %3$s page.', 'seo-by-rank-math' ),
'<strong>' . esc_html__( 'WordPress Address (URL)', 'seo-by-rank-math' ) . '</strong>',
'<strong>' . esc_html__( 'Site Address (URL)', 'seo-by-rank-math' ) . '</strong>',
'<a href="' . esc_url( admin_url( 'options-general.php' ) ) . '">' . esc_html__( 'WordPress General Settings', 'seo-by-rank-math' ) . '</a>'
);
?>
</p>
<?php
}
}
}
@@ -0,0 +1,123 @@
<?php
/**
* The admin bootstrap of the plugin.
*
* @since 1.0.9
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Helper;
use RankMath\Updates;
use RankMath\Traits\Hooker;
defined( 'ABSPATH' ) || exit;
/**
* Admin_Init class.
*
* @codeCoverageIgnore
*/
class Admin_Init {
use Hooker;
/**
* The Constructor.
*/
public function __construct() {
rank_math()->admin = new Admin();
rank_math()->admin_assets = new Assets();
$this->load_review_reminders();
$this->load_pro_notice();
$this->load_setup_wizard();
$this->load_post_columns_and_filters();
$this->run(
[
rank_math()->admin,
rank_math()->admin_assets,
new Admin_Menu(),
new Option_Center(),
new Notices(),
new CMB2_Fields(),
new Metabox\Metabox(),
new Import_Export(),
new Updates(),
new Watcher(),
]
);
/**
* Fires when admin is loaded.
*/
$this->do_action( 'admin/loaded' );
}
/**
* Load out post list and edit screen class.
*/
private function load_post_columns_and_filters() {
$this->run( [ new Bulk_Actions() ] );
if ( Admin_Helper::is_post_list() || Admin_Helper::is_media_library() || Admin_Helper::is_term_listing() || wp_doing_ajax() ) {
$this->run(
[
new Post_Columns(),
new Post_Filters(),
]
);
}
}
/**
* Load review tab in metabox & footer notice.
*/
private function load_review_reminders() {
if ( get_option( 'rank_math_already_reviewed' ) ) {
return;
}
$this->run( [ new Ask_Review() ] );
}
/**
* Load Pro reminder notice.
*/
private function load_pro_notice() {
if ( ! is_main_site() ) {
return;
}
if ( defined( 'RANK_MATH_PRO_FILE' ) || get_option( 'rank_math_already_upgraded' ) ) {
return;
}
$this->run( [ new Pro_Notice() ] );
}
/**
* Run all the runners.
*
* @param array $runners Instances of runner classes.
*/
private function run( $runners ) {
foreach ( $runners as $runner ) {
$runner->hooks();
}
}
/**
* Load setup wizard.
*/
private function load_setup_wizard() {
if ( Helper::is_wizard() ) {
new Setup_Wizard();
}
}
}
@@ -0,0 +1,295 @@
<?php
/**
* The admin pages of the plugin.
*
* @since 1.0.9
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\KB;
use RankMath\Helper;
use RankMath\Helpers\Param;
use RankMath\Runner;
use RankMath\Traits\Hooker;
use RankMath\Admin\Page;
defined( 'ABSPATH' ) || exit;
/**
* Admin_Menu class.
*
* @codeCoverageIgnore
*/
class Admin_Menu implements Runner {
use Hooker;
/**
* Register hooks.
*/
public function hooks() {
$this->action( 'init', 'register_pages' );
$this->action( 'admin_menu', 'fix_admin_menu', 999 );
$this->action( 'admin_head', 'icon_css' );
}
/**
* Register admin pages for plugin.
*/
public function register_pages() {
$this->maybe_deregister();
if ( Helper::is_invalid_registration() && ! is_network_admin() ) {
return;
}
$current_user = wp_get_current_user();
$capabilities = array_keys( Helper::get_roles_capabilities() );
if ( empty( array_intersect( $current_user->roles, $capabilities ) ) && ! current_user_can( 'setup_network' ) ) {
return;
}
$modules = rank_math()->manager->modules;
$data = [];
foreach ( $modules as $id => $module ) {
$data[ $id ] = array_merge(
[
'id' => $module->get_id(),
'isActive' => $module->is_active(),
'isHidden' => $module->is_hidden(),
'isPro' => $module->is_pro_module(),
],
$module->get_args()
);
}
// Dashboard / Welcome / About.
new Page(
'rank-math',
esc_html__( 'Rank Math', 'seo-by-rank-math' ),
[
'position' => 50,
'menu_title' => 'Rank Math',
'capability' => 'manage_options',
'icon' => 'data:image/svg+xml;base64,' . \base64_encode( '<svg viewBox="0 0 462.03 462.03" xmlns="http://www.w3.org/2000/svg" width="20"><g fill="#fff"><path d="m462 234.84-76.17 3.43 13.43 21-127 81.18-126-52.93-146.26 60.97 10.14 24.34 136.1-56.71 128.57 54 138.69-88.61 13.43 21z"/><path d="m54.1 312.78 92.18-38.41 4.49 1.89v-54.58h-96.67zm210.9-223.57v235.05l7.26 3 89.43-57.05v-181zm-105.44 190.79 96.67 40.62v-165.19h-96.67z"/></g></svg>' ), // phpcs:ignore -- This should not cause any issue as we only pass a static svg code.
'render' => Admin_Helper::get_view( 'dashboard' ),
'classes' => [ 'rank-math-page' ],
'assets' => [
'styles' => [ 'rank-math-dashboard' => '' ],
'scripts' => [
'lodash' => '',
'rank-math-components' => '',
'rank-math-dashboard' => '',
'rank-math-modules' => rank_math()->plugin_url() . 'assets/admin/js/modules.js',
],
'json' => [
'isPro' => defined( 'RANK_MATH_PRO_FILE' ),
'isSiteConnected' => Helper::is_site_connected(),
'registerProductNonce' => wp_create_nonce( 'rank_math_register_product' ),
'activateUrl' => Admin_Helper::get_activate_url(),
'isSiteUrlValid' => Admin_Helper::is_site_url_valid(),
'isAdvancedMode' => Helper::is_advanced_mode(),
'contentAiPlan' => Helper::get_content_ai_plan(),
'data' => $data,
'isPluginActiveForNetwork' => Helper::is_plugin_active_for_network(),
'isNetworkAdmin' => is_network_admin(),
'canUser' => [
'manageOptions' => current_user_can( 'manage_options' ),
'setupNetwork' => current_user_can( 'setup_network' ),
'installPlugins' => current_user_can( 'install_plugins' ),
],
],
],
'is_network' => is_network_admin() && Helper::is_plugin_active_for_network(),
]
);
}
/**
* Fix menu names.
*/
public function fix_admin_menu() {
// Replace the main menu name "Rank Math" with "Rank Math SEO".
global $menu;
foreach ( $menu as $key => $item ) {
if ( 'Rank Math' === $item[0] ) {
$menu[ $key ][0] = esc_html__( 'Rank Math SEO', 'seo-by-rank-math' ); // phpcs:ignore -- This is required to change the menu name without changing its slug `rank-math`
break;
}
}
// Replace the first submenu name "Rank Math" with "Dashboard".
global $submenu;
if ( ! isset( $submenu['rank-math'] ) ) {
return;
}
if ( 'Rank Math' === $submenu['rank-math'][0][0] ) {
if ( current_user_can( 'manage_options' ) ) {
$plan = Helper::get_content_ai_plan();
$notification = ( empty( $plan ) || 'free' === $plan ) && get_option( 'rank_math_view_modules' ) ? ' <span class="awaiting-mod count-1"><span class="pending-count" aria-hidden="true">1</span></span>' : '';
$submenu['rank-math'][0][0] = esc_html__( 'Dashboard', 'seo-by-rank-math' ) . $notification; // phpcs:ignore -- This is required to change the menu name when the plugin is not configured.
} else {
unset( $submenu['rank-math'][0] );
}
}
if ( empty( $submenu['rank-math'] ) ) {
return;
}
$submenu['rank-math'][] = [ esc_html__( 'Help &amp; Support', 'seo-by-rank-math' ) . '<i class="dashicons dashicons-external" style="font-size:12px;vertical-align:-2px;height:10px;"></i>', 'manage_options', KB::get( 'knowledgebase', 'Sidebar Help Link' ) ]; // phpcs:ignore -- A custom link to our KB article.
$this->add_offer_link( $submenu );
// Store ID of first_menu item so we can use it in the Admin menu item.
set_transient( 'rank_math_first_submenu_id', array_values( $submenu['rank-math'] )[0][2] );
}
/**
* Print icon CSS for admin menu bar.
*/
public function icon_css() {
?>
<script type="text/javascript">
// Open RM KB menu link in the new tab.
jQuery( document ).ready( function( $ ) {
$( "ul#adminmenu a[href$='<?php KB::the( 'knowledgebase', 'Sidebar Help Link' ); ?>']" ).attr( 'target', '_blank' )
$( "ul#adminmenu a[href$='<?php echo esc_url_raw( $this->get_offer_link() ); ?>']" ).attr( 'target', '_blank' )
} );
</script>
<style>
#wp-admin-bar-rank-math .rank-math-icon {
display: inline-block;
top: 6px;
position: relative;
padding-right: 10px;
max-width: 20px;
}
#wp-admin-bar-rank-math .rank-math-icon svg {
fill-rule: evenodd;
fill: #dedede;
}
#wp-admin-bar-rank-math:hover .rank-math-icon svg {
fill-rule: evenodd;
fill: #00b9eb;
}
#adminmenu #toplevel_page_rank-math:not(.wp-has-submenu) {
display: none;
}
.multisite.network-admin #toplevel_page_rank-math {
display: block;
}
#adminmenu #toplevel_page_rank-math a[href$='<?php echo esc_url_raw( $this->get_offer_link() ); ?>'],
#adminmenu #toplevel_page_rank-math a[href$='<?php echo esc_url_raw( $this->get_offer_link() ); ?>']:hover,
#adminmenu #toplevel_page_rank-math a[href$='<?php echo esc_url_raw( $this->get_offer_link() ); ?>']:focus {
background-color: #10AC84;
color: #fff;
}
</style>
<?php
}
/**
* Check for deactivation.
*/
private function maybe_deregister() {
if ( ! Helper::has_cap( 'general' ) || 'deregister' !== Param::post( 'registration-action' ) ) {
return;
}
$nonce = Param::post( '_wpnonce' );
if ( ! $nonce || ! wp_verify_nonce( $nonce, 'rank_math_register_product' ) ) {
return;
}
Admin_Helper::deregister_user();
}
/**
* Function to add Offer link based on the date range.
*
* @param array $submenu Submenu items.
*/
private function add_offer_link( &$submenu ) {
$offer = $this->get_active_offer();
if ( ! $offer ) {
return;
}
$submenu['rank-math'][] = [ current( $offer ) . '&nbsp;', 'manage_options', $this->get_offer_link() ];
}
/**
* Get the offer link.
*/
private function get_offer_link() {
return KB::get( 'pro', 'upgrade-dashboard-notifications-menu' );
}
/**
* Function to get active offer
*/
private function get_active_offer() {
// Early Bail if PRO plugin is active.
if ( defined( 'RANK_MATH_PRO_FILE' ) ) {
return false;
}
$timezone = new \DateTimeZone( 'Asia/Kolkata' );
$current_date = new \DateTime( 'now', $timezone );
$dates = [
'halloween' => [
'start' => '2026-10-28',
'end' => '2026-11-03',
'text' => esc_html__( 'Halloween Sale', 'seo-by-rank-math' ),
],
'anniversary' => [
'start' => '2026-11-04',
'end' => '2026-11-10',
'text' => esc_html__( 'Anniversary Sale', 'seo-by-rank-math' ),
],
'black-friday' => [
'start' => '2026-11-11',
'end' => '2026-11-27',
'text' => esc_html__( 'Black Friday Sale', 'seo-by-rank-math' ),
],
'cyber-monday' => [
'start' => '2026-11-28',
'end' => '2026-12-02',
'text' => esc_html__( 'Cyber Monday Sale', 'seo-by-rank-math' ),
],
'christmas' => [
'start' => '2026-12-24',
'end' => '2026-12-31',
'text' => esc_html__( 'Christmas Sale', 'seo-by-rank-math' ),
],
'new-year' => [
'start' => '2027-01-01',
'end' => '2027-01-07',
'text' => esc_html__( 'New Year Sale', 'seo-by-rank-math' ),
],
];
$active_offer = [
'unlock-pro' => esc_html__( 'Unlock PRO', 'seo-by-rank-math' ),
];
foreach ( $dates as $key => $date ) {
$start_date = new \DateTime( $date['start'] . ' 16:00:00', $timezone );
$end_date = new \DateTime( $date['end'] . ' 16:00:00', $timezone );
if ( $current_date >= $start_date && $current_date <= $end_date ) {
$active_offer = [ $key => $date['text'] ];
break;
}
}
return $active_offer;
}
}
@@ -0,0 +1,568 @@
<?php
/**
* The admin-specific functionality of the plugin.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Runner;
use RankMath\Helper;
use RankMath\Helpers\Str;
use RankMath\Helpers\DB as DB_Helper;
use RankMath\Helpers\Param;
use RankMath\Admin\Admin_Helper;
use RankMath\Traits\Ajax;
use RankMath\Traits\Hooker;
defined( 'ABSPATH' ) || exit;
/**
* Admin class.
*
* @codeCoverageIgnore
*/
class Admin implements Runner {
use Hooker;
use Ajax;
/**
* Register hooks.
*/
public function hooks() {
$this->action( 'init', 'flush', 999 );
$this->filter( 'user_contactmethods', 'update_user_contactmethods' );
$this->action( 'profile_update', 'profile_update', 10, 3 );
$this->action( 'admin_footer', 'convert_additional_profile_url_to_textarea' );
$this->action( 'save_post', 'canonical_check_notice' );
$this->action( 'cmb2_save_options-page_fields', 'update_is_configured_value', 10, 2 );
$this->filter( 'action_scheduler_pastdue_actions_check_pre', 'as_exclude_pastdue_actions' );
$this->filter( 'rank_math/pro_badge', 'offer_icon' );
$this->filter( 'load_script_translation_file', 'load_script_translation_file', 10, 3 );
// Use woocommerce textdomain for the Actiion scheduler strings.
$this->filter( 'gettext', 'remap_action_scheduler_translation', 10, 3 );
$this->filter( 'gettext_with_context', 'remap_action_scheduler_translation_with_context', 10, 4 );
// AJAX.
$this->ajax( 'search_pages', 'search_pages' );
$this->ajax( 'is_keyword_new', 'is_keyword_new' );
$this->ajax( 'save_checklist_layout', 'save_checklist_layout' );
$this->ajax( 'deactivate_plugins', 'deactivate_plugins' );
}
/**
* Update user profile.
*
* @param int $user_id The user ID.
* @param array $old_user_data Old user data.
* @param array $userdata User data.
*/
public function profile_update( $user_id, $old_user_data, $userdata ) {
if ( ! current_user_can( 'edit_user', $user_id ) ) {
return false;
}
$nonce = Param::post( '_wpnonce', '', FILTER_SANITIZE_SPECIAL_CHARS );
if ( ! wp_verify_nonce( $nonce, 'update-user_' . $user_id ) ) {
return false;
}
$twitter = Param::post( 'twitter', '', FILTER_SANITIZE_URL );
$facebook = Param::post( 'facebook', '', FILTER_SANITIZE_URL );
$additional_profile_urls = Param::post( 'additional_profile_urls', '' );
if ( $additional_profile_urls ) {
$additional_profile_urls = array_map( 'sanitize_url', explode( PHP_EOL, $additional_profile_urls ) );
$additional_profile_urls = implode( ' ', $additional_profile_urls );
}
update_user_meta( $user_id, 'twitter', $twitter );
update_user_meta( $user_id, 'facebook', $facebook );
update_user_meta( $user_id, 'additional_profile_urls', $additional_profile_urls );
}
/**
* Flush the rewrite rules once if the rank_math_flush_rewrite option is set.
*/
public function flush() {
if ( get_option( 'rank_math_flush_rewrite' ) ) {
flush_rewrite_rules();
delete_option( 'rank_math_flush_rewrite' );
}
if ( 'rank-math' === Param::get( 'page' ) && get_option( 'rank_math_view_modules' ) ) {
delete_option( 'rank_math_view_modules' );
}
}
/**
* Add Facebook and Twitter as user contact methods.
*
* @param array $contactmethods Current contact methods.
* @return array New contact methods with extra items.
*
* @copyright Copyright (C) 2008-2019, Yoast BV
* The following code is a derivative work of the code from the Yoast(https://github.com/Yoast/wordpress-seo/), which is licensed under GPL v3.
*/
public function update_user_contactmethods( $contactmethods ) {
$contactmethods['twitter'] = esc_html__( 'Twitter username (without @)', 'seo-by-rank-math' );
$contactmethods['facebook'] = esc_html__( 'Facebook profile URL', 'seo-by-rank-math' );
$contactmethods['additional_profile_urls'] = esc_html__( 'Additional profile URLs', 'seo-by-rank-math' );
return $contactmethods;
}
/**
* Display admin header.
*
* @param bool $show_breadcrumbs Determines whether to show breadcrumbs or not.
*/
public function display_admin_header( $show_breadcrumbs = true ) {
$nav_tabs = new Admin_Header();
$nav_tabs->display( $show_breadcrumbs );
}
/**
* Display admin breadcrumbs.
*/
public function display_admin_breadcrumbs() {
$nav_tabs = new Admin_Breadcrumbs();
$nav_tabs->display();
}
/**
* Display dashboard tabs.
*/
public function display_dashboard_nav() {
$nav_tabs = new Admin_Dashboard_Nav();
$nav_tabs->display();
}
/**
* Show notice when canonical URL is not a valid URL.
*
* @param int $post_id The post ID.
*/
public function canonical_check_notice( $post_id ) {
$post_type = get_post_type( $post_id );
$is_allowed = in_array( $post_type, Helper::get_allowed_post_types(), true );
if ( ! $is_allowed || Helper::is_autosave() || Helper::is_ajax() || isset( $_REQUEST['bulk_edit'] ) ) { // phpcs:ignore
return $post_id;
}
if ( ! empty( $_POST['rank_math_canonical_url'] ) && false === Param::post( 'rank_math_canonical_url', false, FILTER_VALIDATE_URL ) ) { // phpcs:ignore
$message = esc_html__( 'The canonical URL you entered does not seem to be a valid URL. Please double check it in the SEO meta box &raquo; Advanced tab.', 'seo-by-rank-math' );
Helper::add_notification( $message, [ 'type' => 'error' ] );
}
}
/**
* Save checklist layout.
*/
public function save_checklist_layout() {
check_ajax_referer( 'rank-math-ajax-nonce', 'security' );
$this->has_cap_ajax( 'onpage_general' );
if ( empty( $_POST['layout'] ) || ! is_array( $_POST['layout'] ) ) {
return;
}
$layout = Param::post( 'layout', [], FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
$allowed = [
'basic' => 1,
'advanced' => 1,
'title-readability' => 1,
'content-readability' => 1,
];
$layout = array_intersect_key( $layout, $allowed );
update_user_meta( get_current_user_id(), 'rank_math_metabox_checklist_layout', $layout );
exit;
}
/**
* Ajax handler to search pages based on the searched string. Used in the Local SEO Settings.
*/
public function search_pages() {
check_ajax_referer( 'rank-math-ajax-nonce', 'security' );
$this->has_cap_ajax( 'general' );
$term = Param::get( 'term' );
if ( empty( $term ) ) {
exit;
}
global $wpdb;
$pages = DB_Helper::get_results(
$wpdb->prepare(
"SELECT ID, post_title FROM {$wpdb->prefix}posts WHERE post_type = 'page' AND post_status = 'publish' AND post_title LIKE %s",
"%{$wpdb->esc_like( $term )}%"
),
ARRAY_A
);
$data = [];
foreach ( $pages as $page ) {
$data[] = [
'id' => $page['ID'],
'text' => $page['post_title'],
'url' => get_permalink( $page['ID'] ),
];
}
wp_send_json( [ 'results' => $data ] );
}
/**
* Check if the keyword has been used before for another post.
*/
public function is_keyword_new() {
global $wpdb;
check_ajax_referer( 'rank-math-ajax-nonce', 'security' );
$this->has_cap_ajax( 'onpage_general' );
$result = [ 'isNew' => true ];
if ( empty( $_GET['keyword'] ) ) {
$this->success( $result );
}
$keyword = Param::get( 'keyword', '', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK );
$object_id = Param::get( 'objectID', 0, FILTER_VALIDATE_INT );
$object_type = Param::get( 'objectType', '', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK );
$column_ids = [
'post' => 'ID',
'term' => 'term_id',
'user' => 'ID',
];
if ( ! in_array( $object_type, [ 'post', 'term', 'user' ], true ) ) {
$object_type = 'post';
}
$main = $wpdb->{$object_type . 's'};
$meta = $wpdb->{$object_type . 'meta'};
$query = sprintf( 'select %2$s.%1$s from %2$s inner join %3$s on %2$s.%1$s = %3$s.%4$s_id where ', $column_ids[ $object_type ], $main, $meta, $object_type );
if ( 'post' === $object_type ) {
$query .= sprintf( '%s.post_status = \'publish\' and ', $main );
}
$query .= sprintf( '%1$s.meta_key = \'rank_math_focus_keyword\' and ( %1$s.meta_value = %2$s OR %1$s.meta_value like %3$s ) and %1$s.%4$s_id != %5$d', $meta, '%s', '%s', $object_type, $object_id );
$data = DB_Helper::get_row( $wpdb->prepare( $query, $keyword, $wpdb->esc_like( $keyword ) . ',%' ) );
$result['isNew'] = empty( $data );
$this->success( $result );
}
/**
* Get link suggestions for the current post.
*
* @param int|WP_Post $post Current post.
* @return array
*/
public function get_link_suggestions( $post ) {
global $pagenow;
if ( 'post-new.php' === $pagenow ) {
return;
}
$output = [];
$post = get_post( $post );
$args = [
'post_type' => $post->post_type,
'post__not_in' => [ $post->ID ],
'posts_per_page' => 5,
'meta_key' => 'rank_math_pillar_content',
'meta_value' => 'on',
'tax_query' => [ 'relation' => 'OR' ],
];
$taxonomies = Helper::get_object_taxonomies( $post, 'names' );
$taxonomies = array_filter( $taxonomies, [ $this, 'is_taxonomy_allowed' ] );
foreach ( $taxonomies as $taxonomy ) {
$this->set_term_query( $args, $post->ID, $taxonomy );
}
$posts = get_posts( $args );
foreach ( $posts as $related_post ) {
$item = [
'title' => get_the_title( $related_post->ID ),
'url' => get_permalink( $related_post->ID ),
'post_id' => $related_post->ID,
'focus_keywords' => get_post_meta( $related_post->ID, 'rank_math_focus_keyword', true ),
];
$item['focus_keywords'] = empty( $item['focus_keywords'] ) ? [] : explode( ',', $item['focus_keywords'] );
$output[] = $item;
}
return $output;
}
/**
* Is taxonomy allowed
*
* @param string $taxonomy Taxonomy to check.
*
* @return bool
*/
public function is_taxonomy_allowed( $taxonomy ) {
$exclude_taxonomies = [ 'post_format', 'product_shipping_class' ];
if ( Str::starts_with( 'pa_', $taxonomy ) || in_array( $taxonomy, $exclude_taxonomies, true ) ) {
return false;
}
return true;
}
/**
* Remap Action Scheduler translation to use WooCommerce's text domain (no context).
*
* @param string $translated Translated text.
* @param string $text Original text.
* @param string $domain Text domain.
* @return string Modified translated text.
*/
public function remap_action_scheduler_translation( $translated, $text, $domain ) {
if ( ! self::should_remap_action_scheduler_translation( $domain ) ) {
return $translated;
}
return self::get_translated_string( $translated, $text );
}
/**
* Remap Action Scheduler translation to use WooCommerce's text domain (with context).
*
* @param string $translated Translated text.
* @param string $text Original text.
* @param string $context Context information for translators.
* @param string $domain Text domain.
* @return string Modified translated text.
*/
public function remap_action_scheduler_translation_with_context( $translated, $text, $context, $domain ) {
if ( ! self::should_remap_action_scheduler_translation( $domain ) ) {
return $translated;
}
return self::get_translated_string( $translated, $text, $context );
}
/**
* Determine whether to remap Action Scheduler translations to WooCommerce's text domain.
*
* @param string $domain Text domain.
* @return bool True if the translation should be remapped, false otherwise.
*/
private static function should_remap_action_scheduler_translation( $domain ) {
return 'action-scheduler' === $domain && Helper::is_woocommerce_active();
}
/**
* Get the translated string from WooCommerce's text domain if the original string matches an Action Scheduler string.
*
* @param string $translated Translated text.
* @param string $text Original text.
* @param string|null $context Context information for translators.
*
* @return string Modified translated text.
*/
private static function get_translated_string( $translated, $text, $context = null ) {
$translations = get_translations_for_domain( 'woocommerce' );
$translation = $translations->translate( $text, $context );
return $translation !== $text ? $translation : $translated;
}
/**
* Set term query.
*
* @param array $query Array of query.
* @param int $post_id Post ID to get terms from.
* @param string $taxonomy Taxonomy to get terms for.
*/
private function set_term_query( &$query, $post_id, $taxonomy ) {
$terms = wp_get_post_terms( $post_id, $taxonomy, [ 'fields' => 'ids' ] );
if ( empty( $terms ) || is_wp_error( $terms ) ) {
return;
}
$query['tax_query'][] = [
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $terms,
];
}
/**
* Output link suggestions.
*
* @deprecated 1.0.273 Link suggestions are now rendered by the React component.
*
* @param array $suggestions Link items.
* @return string
*/
public function get_link_suggestions_html( $suggestions ) {
_deprecated_function( __METHOD__, '1.0.273' );
return '';
}
/**
* Updates the is_configured value.
*
* @param int $object_id The ID of the current object.
* @param string $cmb_id The current box ID.
*/
public function update_is_configured_value( $object_id, $cmb_id ) {
if ( 0 !== strpos( $cmb_id, 'rank_math' ) && 0 !== strpos( $cmb_id, 'rank-math' ) ) {
return;
}
Helper::is_configured( true );
}
/**
* Deactivate plugin.
*/
public function deactivate_plugins() {
check_ajax_referer( 'rank-math-ajax-nonce', 'security' );
if ( ! current_user_can( 'activate_plugins' ) ) {
$this->error( esc_html__( 'You are not authorized to perform this action.', 'seo-by-rank-math' ) );
}
$plugin = Param::post( 'plugin', '', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK );
if ( 'all' !== $plugin ) {
deactivate_plugins( $plugin );
die( '1' );
}
Importers\Detector::deactivate_all();
die( '1' );
}
/**
* Action Scheduler: exclude our actions from the past-due checker.
* Since this is a *_pre hook, it replaces the original checker.
*
* We first do the same check as what ActionScheduler_AdminView->check_pastdue_actions() does,
* but then we also count how many of those past-due actions are ours.
*
* @param null $value Null value.
*/
public function as_exclude_pastdue_actions( $value ) {
$query_args = [
'date' => as_get_datetime_object( time() - DAY_IN_SECONDS ),
'status' => \ActionScheduler_Store::STATUS_PENDING,
'per_page' => 1,
];
$store = \ActionScheduler_Store::instance();
$num_pastdue_actions = (int) $store->query_actions( $query_args, 'count' );
if ( 0 !== $num_pastdue_actions ) {
$query_args['group'] = 'rank-math';
$num_pastdue_rm_actions = (int) $store->query_actions( $query_args, 'count' );
$num_pastdue_actions -= $num_pastdue_rm_actions;
}
$threshold_seconds = (int) apply_filters( 'action_scheduler_pastdue_actions_seconds', DAY_IN_SECONDS );
$threshold_min = (int) apply_filters( 'action_scheduler_pastdue_actions_min', 1 );
$check = ( $num_pastdue_actions >= $threshold_min );
return (bool) apply_filters( 'action_scheduler_pastdue_actions_check', $check, $num_pastdue_actions, $threshold_seconds, $threshold_min );
}
/**
* Check and print the Anniversary icon in the header of Rank Math's setting pages.
*/
public static function offer_icon() {
if ( ! current_user_can( 'manage_options' ) || defined( 'RANK_MATH_PRO_FILE' ) ) {
return;
}
// Holiday Season related variables.
$time = time();
$current_year = 2025;
$anniversary_start_time = gmmktime( 17, 00, 00, 10, 29, $current_year ); // 29 Oct.
$anniversary_end_time = gmmktime( 17, 00, 00, 12, 03, $current_year ); // 30 Nov.
$holiday_start_time = gmmktime( 17, 00, 00, 12, 24, $current_year ); // 20 Dec.
$holiday_end_time = gmmktime( 17, 00, 00, 01, 07, 2026 ); // 07 Jan.
ob_start();
if (
( $time > $anniversary_start_time && $time < $anniversary_end_time ) ||
( $time > $holiday_start_time && $time < $holiday_end_time )
) { ?>
<a href="<?php echo esc_url( \RankMath\KB::get( 'pro', 'Header Offer Icon' ) ); ?>" target="_blank" class="rank-math-tooltip bottom" style="margin-left:5px;">
🎉
<span><?php esc_attr_e( 'Exclusive Offer!', 'seo-by-rank-math' ); ?></span>
</a>
<?php
}
return ob_get_clean();
}
/**
* Code to convert Addiontal Profile URLs from input type text to textarea.
*/
public function convert_additional_profile_url_to_textarea() {
if ( ! Admin_Helper::is_user_edit() ) {
return;
}
$field_description = __( 'Additional Profiles to add in the <code>sameAs</code> Schema property.', 'seo-by-rank-math' );
?>
<script type="text/javascript">
( function( $ ) {
$( function() {
const twitterWrapper = $( '.user-twitter-wrap' );
twitterWrapper.before( '<tr><th><h2 style="margin: 0;">Rank Math SEO</h2></th><td></td></tr>' );
const additionalProfileField = $( '#additional_profile_urls' );
if ( ! additionalProfileField.length ) {
return
}
var $txtarea = $( '<textarea />' );
$txtarea.attr( 'id', additionalProfileField[0].id );
$txtarea.attr( 'name', additionalProfileField[0].name );
$txtarea.attr( 'rows', 5 );
$txtarea.val( additionalProfileField[0].value.replaceAll( " ", "\n" ) );
additionalProfileField.replaceWith( $txtarea );
$( '<p class="description"><?php echo wp_kses_post( $field_description ); ?></p>' ).insertAfter( $txtarea );
} );
})(jQuery);
</script>
<?php
}
/**
* Function to replace domain with seo-by-rank-math in translation file.
*
* @param string|false $file Path to the translation file to load. False if there isn't one.
* @param string $handle Name of the script to register a translation domain to.
* @param string $domain The text domain.
*/
public function load_script_translation_file( $file, $handle, $domain ) {
if ( 'rank-math' !== $domain ) {
return $file;
}
$data = explode( '/', $file );
$data[ count( $data ) - 1 ] = preg_replace( '/rank-math/', 'seo-by-rank-math', $data[ count( $data ) - 1 ], 1 );
return implode( '/', $data );
}
}
@@ -0,0 +1,278 @@
<?php
/**
* The RankMath API.
*
* @since 1.5.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use WP_Error;
/**
* Api class.
*/
class Api {
/**
* Rank Math SEO Checkup API.
*
* @var string
*/
protected $api_url = 'https://rankmath.com/wp-json/rankmath/v1/';
/**
* Was the last request successful.
*
* @var bool
*/
protected $is_success = false;
/**
* Last error.
*
* @var string
*/
protected $last_error = '';
/**
* Last response.
*
* @var array
*/
protected $last_response = [];
/**
* Last response header code.
*
* @var int
*/
protected $last_code = 0;
/**
* User agent.
*
* @var string
*/
protected $user_agent = '';
/**
* Is blocking.
*
* @var bool
*/
protected $is_blocking = true;
/**
* Main instance
*
* Ensure only one instance is loaded or can be loaded.
*
* @return Api
*/
public static function get() {
static $instance;
if ( is_null( $instance ) && ! ( $instance instanceof Api ) ) {
$instance = new Api();
$instance->is_blocking = true;
$instance->user_agent = 'RankMath/' . md5( esc_url( home_url( '/' ) ) );
}
return $instance;
}
/**
* Was the last request successful?
*
* @return bool True for success, false for failure
*/
public function is_success() {
return $this->is_success;
}
/**
* Get the last error returned by either the network transport, or by the API.
* If something didn't work, this should contain the string describing the problem.
*
* @return array|false describing the error
*/
public function get_error() {
return $this->last_error ? $this->last_error : false;
}
/**
* Get an array containing the HTTP headers and the body of the API response.
*
* @return array Assoc array with keys 'headers' and 'body'
*/
public function get_response() {
return $this->last_response;
}
/**
* Remove registration data and disconnect from RankMath.com.
*
* @param string $username Username.
* @param string $api_key Api key.
*/
public function deactivate_site( $username, $api_key ) {
$this->is_blocking = false;
$data = wp_json_encode(
[
'username' => $username,
'api_key' => $api_key,
'site_url' => esc_url( home_url() ),
]
);
$response = wp_remote_post(
RANK_MATH_SITE_URL . '/wp-json/rankmath/v1/deactivateSite',
[
'body' => $data,
'headers' => [
'Content-Type' => 'application/json',
],
],
);
}
/**
* Make an HTTP GET request - for retrieving data.
*
* @param string $url URL to do request.
* @param array $args Assoc array of arguments (usually your data).
* @param int $timeout Timeout limit for request in seconds.
*
* @return array|false Assoc array of API response, decoded from JSON.
*/
public function http_get( $url, $args = [], $timeout = 10 ) {
return $this->make_request( 'GET', $url, $args, $timeout );
}
/**
* Make an HTTP POST request - for creating and updating items.
*
* @param string $url URL to do request.
* @param array $args Assoc array of arguments (usually your data).
* @param int $timeout Timeout limit for request in seconds.
*
* @return array|false Assoc array of API response, decoded from JSON.
*/
public function http_post( $url, $args = [], $timeout = 10 ) {
return $this->make_request( 'POST', $url, $args, $timeout );
}
/**
* Make an HTTP PUT request - for creating new items.
*
* @param string $url URL to do request.
* @param array $args Assoc array of arguments (usually your data).
* @param int $timeout Timeout limit for request in seconds.
*
* @return array|false Assoc array of API response, decoded from JSON.
*/
public function http_put( $url, $args = [], $timeout = 10 ) {
return $this->make_request( 'PUT', $url, $args, $timeout );
}
/**
* Make an HTTP DELETE request - for deleting data.
*
* @param string $url URL to do request.
* @param array $args Assoc array of arguments (usually your data).
* @param int $timeout Timeout limit for request in seconds.
*
* @return array|false Assoc array of API response, decoded from JSON.
*/
public function http_delete( $url, $args = [], $timeout = 10 ) {
return $this->make_request( 'DELETE', $url, $args, $timeout );
}
/**
* Performs the underlying HTTP request. Not very exciting.
*
* @param string $http_verb The HTTP verb to use: get, post, put, patch, delete.
* @param string $url URL to do request.
* @param array $args Assoc array of parameters to be passed.
* @param int $timeout Timeout limit for request in seconds.
*
* @return array|false Assoc array of decoded result.
*/
protected function make_request( $http_verb, $url, $args = [], $timeout = 10 ) {
$params = [
'timeout' => $timeout,
'method' => $http_verb,
'user-agent' => $this->user_agent,
'blocking' => $this->is_blocking,
];
if ( ! empty( $args ) && is_array( $args ) ) {
$params['body'] = $args;
}
$this->reset();
$response = wp_remote_request( $this->api_url . $url, $params );
$this->determine_success( $response );
return $this->format_response( $response );
}
/**
* Decode the response and format any error messages for debugging
*
* @param array|WP_Error $response The response from the curl request.
*
* @return array|false The JSON decoded into an array
*/
protected function format_response( $response ) {
$this->last_response = $response;
if ( is_wp_error( $response ) ) {
return false;
}
if ( ! empty( $response['body'] ) ) {
return json_decode( $response['body'], true );
}
return false;
}
/**
* Check if the response was successful or a failure. If it failed, store the error.
*
* @param array|WP_Error $response The response from the curl request.
*/
protected function determine_success( $response ) {
if ( is_wp_error( $response ) ) {
$this->last_error = 'WP_Error: ' . $response->get_error_message();
return;
}
$this->last_code = wp_remote_retrieve_response_code( $response );
if ( in_array( $this->last_code, [ 200, 204 ], true ) ) {
$this->is_success = true;
return;
}
$this->last_error = 'Unknown error, call getLastResponse() to find out what happened.';
}
/**
* Reset request.
*/
protected function reset() {
$this->last_code = 0;
$this->last_error = '';
$this->is_success = false;
$this->is_blocking = true;
$this->last_response = [
'body' => null,
'headers' => null,
];
}
}
@@ -0,0 +1,262 @@
<?php
/**
* Ask user to review Rank Math on wp.org, in the meta box after 2 weeks.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Helper;
use RankMath\Traits\Ajax;
use RankMath\Traits\Hooker;
defined( 'ABSPATH' ) || exit;
/**
* Ask_Review class.
*/
class Ask_Review {
use Hooker;
use Ajax;
/**
* Now.
*
* @var string
*/
public $current_time = '';
/**
* Date of release of version 1.0.57. Turned into a timestamp in the constructor.
*
* @var string
*/
public $record_date = '2021-02-03 13:00';
/**
* Rank Math plugin install date.
*
* @var string
*/
public $install_date = '';
/**
* Constructor method.
*/
public function __construct() {
$this->current_time = Helper::get_current_time();
$this->record_date = strtotime( $this->record_date );
$this->install_date = get_option( 'rank_math_install_date' );
if ( false === $this->install_date ) {
$this->install_date = $this->current_time;
}
}
/**
* Register hooks.
*/
public function hooks() {
$this->ajax( 'already_reviewed', 'already_reviewed' );
// Post editor tab.
if ( $this->current_time > $this->install_date + ( 10 * DAY_IN_SECONDS ) ) {
Helper::add_json( 'showReviewTab', true );
}
// Admin notice.
$review_notice_date = $this->get_review_notice_date();
if ( $this->current_time > $review_notice_date ) {
if ( get_option( 'rank_math_review_notice_added' ) === false && ! Helper::has_notification( 'rank_math_pro_notice' ) ) {
$this->add_notice();
}
// Make dismiss button work like the "Maybe later" link.
$this->action( 'wp_helpers_notification_dismissed', 'review_notice_after_dismiss' );
}
$this->action( 'admin_footer', 'review_notice_js', 15 );
}
/**
* Add inline JS related to the review notice.
*
* @return void
*/
public function review_notice_js() {
if ( ! Helper::has_notification( 'rank_math_review_plugin_notice' ) ) {
return;
}
?>
<script>
(function( $ ) {
$( function() {
$('.rank-math-dismiss-review-notice').on( 'click', function(e) {
var $this = $(this);
if ( ! $this.hasClass( 'rank-math-review-action' ) ) {
e.preventDefault();
}
if ( $this.hasClass( 'rank-math-maybe-later-action' ) ) {
$('#rank_math_review_plugin_notice').find( '.notice-dismiss' ).trigger('click');
return false;
}
jQuery.ajax( {
url: rankMath.ajaxurl,
data: { action: 'rank_math_already_reviewed', security: rankMath.security,
},
} );
$('#rank_math_review_plugin_notice').find( '.notice-dismiss' ).trigger('click');
});
});
})(jQuery);
</script>
<style>
#rank_math_review_plugin_notice .rank-math-notice.is-dismissible a,
#rank_math_pro_notice .rank-math-notice.is-dismissible a {
color: #4f52d4;
}
#rank_math_review_plugin_notice.is-dismissible,
#rank_math_pro_notice.is-dismissible {
border-width: 0 0 0 4px;
border-left-color: #6668BD;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15);
padding: 5px 10px 5px 65px;
}
#rank_math_review_plugin_notice.is-dismissible:before,
#rank_math_pro_notice.is-dismissible:before {
content: '';
width: 50px;
height: 100%;
background: rgba(102, 104, 189, 0.09);
position: absolute;
left: 0;
top: 0;
}
#rank_math_review_plugin_notice.is-dismissible:after,
#rank_math_pro_notice.is-dismissible:after {
content: url('data:image/svg+xml;charset=UTF-8, <svg viewBox="0 0 462.03 462.03" xmlns="http://www.w3.org/2000/svg" width="20"><g fill="white"><path d="m462 234.84-76.17 3.43 13.43 21-127 81.18-126-52.93-146.26 60.97 10.14 24.34 136.1-56.71 128.57 54 138.69-88.61 13.43 21z"></path><path d="m54.1 312.78 92.18-38.41 4.49 1.89v-54.58h-96.67zm210.9-223.57v235.05l7.26 3 89.43-57.05v-181zm-105.44 190.79 96.67 40.62v-165.19h-96.67z"></path></g></svg>' );
padding: 3px;
border-radius: 3px;
position: absolute;
left: 12px;
top: 18px;
background: linear-gradient(-135deg, #2488e1, #724bb7);
width: 23px;
height: 23px;
display: flex;
justify-content: center;
line-height: 1;
align-items: center;
}
</style>
<?php
}
/**
* Add admin notice.
*
* @return void
*/
public function add_notice() {
// 50-50 split between WordPress.org and Trustpilot.
$show_wordpress = (bool) wp_rand( 0, 1 );
if ( $show_wordpress ) {
$selected_link = 'https://wordpress.org/support/plugin/seo-by-rank-math/reviews/?filter=5#new-post';
} else {
// If Trustpilot, pick one of the two links (50-50).
$review_links = [
'https://www.trustpilot.com/review/www.rankmath.com',
'https://www.trustpilot.com/evaluate/www.rankmath.com',
];
$selected_link = $review_links[ array_rand( $review_links ) ];
}
$message = '<p>';
// Translators: placeholder is the plugin name.
$message .= sprintf( esc_html__( 'Hey, we noticed you\'ve been using %s for more than a week now – that\'s awesome!', 'seo-by-rank-math' ), '<strong>' . _x( 'Rank Math SEO', 'plugin name inside the review notice', 'seo-by-rank-math' ) . '</strong>' );
$message .= '<br>';
if ( $show_wordpress ) {
$message .= esc_html__( 'We would love to get your feedback! It\'s essential for our continued development. Please consider taking a moment to leave us a review.', 'seo-by-rank-math' );
} else {
$message .= esc_html__( 'We would love to get your feedback! It\'s essential for our continued development. Please consider taking a moment to leave a review of your experience on Trustpilot.', 'seo-by-rank-math' );
}
$message .= '</p>
<p><strong>Bhanu Ahluwalia</strong><br>' . esc_html__( 'Co-founder of Rank Math', 'seo-by-rank-math' ) . '</p>
<p>
<a href="' . esc_url( $selected_link ) . '" class="rank-math-dismiss-review-notice rank-math-review-action rank-math-review-out" target="_blank" rel="noopener noreferrer"><strong>' . esc_html__( 'Yes, you deserve it', 'seo-by-rank-math' ) . '</strong></a><br>
<a href="#" class="rank-math-dismiss-review-notice rank-math-maybe-later-action">' . esc_html__( 'No, maybe later', 'seo-by-rank-math' ) . '</a><br>
<a href="#" class="rank-math-dismiss-review-notice rank-math-already-reviewed-action">' . esc_html__( 'I already did', 'seo-by-rank-math' ) . '</a>
</p>';
Helper::add_notification(
$message,
[
'type' => 'info',
'id' => 'rank_math_review_plugin_notice',
'capability' => 'install_plugins',
]
);
update_option( 'rank_math_review_notice_added', '1', false );
}
/**
* Set "already reviewed" flag after the user dismisses the notice.
*
* @param string $notification_id Dismissed notice ID.
* @return void
*/
public function review_notice_after_dismiss( $notification_id ) {
if ( 'rank_math_review_plugin_notice' !== $notification_id ) {
return;
}
delete_option( 'rank_math_review_notice_date' );
delete_option( 'rank_math_review_notice_added' );
update_option( 'rank_math_review_notice_delayed', true, false );
}
/**
* Get stored notice start date.
*
* @return int
*/
public function get_review_notice_date() {
$review_notice_date = get_option( 'rank_math_review_notice_date' );
if ( false !== $review_notice_date ) {
return $review_notice_date;
}
$delay_days = 14;
if ( $this->install_date < $this->record_date && ! get_option( 'rank_math_review_notice_delayed' ) ) {
$delay_days = wp_rand( 7, 30 );
}
$review_notice_date = $this->current_time + ( $delay_days * DAY_IN_SECONDS );
update_option( 'rank_math_review_notice_date', $review_notice_date, false );
return $review_notice_date;
}
/**
* Set "already reviewed" flag.
*/
public function already_reviewed() {
check_ajax_referer( 'rank-math-ajax-nonce', 'security' );
$this->has_cap_ajax( 'onpage_general' );
update_option( 'rank_math_already_reviewed', Helper::get_current_time() );
$this->success( 'success' );
}
}
@@ -0,0 +1,281 @@
<?php
/**
* Register all the necessary CSS and JS.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\KB;
use RankMath\Helper;
use RankMath\Runner;
use RankMath\Traits\Hooker;
use RankMath\Google\Console;
use RankMath\Google\Analytics;
use RankMath\Analytics\Url_Inspection;
use RankMath\Admin\Admin_Helper;
use RankMath\Helpers\Str;
defined( 'ABSPATH' ) || exit;
/**
* Assets class.
*
* @codeCoverageIgnore
*/
class Assets implements Runner {
use Hooker;
/**
* Prefix for the enqueue handles.
*/
const PREFIX = 'rank-math-';
/**
* Register hooks.
*/
public function hooks() {
$this->action( 'admin_enqueue_scripts', 'register' );
$this->action( 'admin_enqueue_scripts', 'enqueue' );
$this->action( 'admin_enqueue_scripts', 'overwrite_wplink', 99 );
if ( 'elementor' === \RankMath\Helpers\Param::get( 'action' ) ) {
$this->action( 'elementor/editor/before_enqueue_scripts', 'register' );
$this->action( 'elementor/editor/before_enqueue_scripts', 'enqueue' );
$this->action( 'elementor/editor/before_enqueue_scripts', 'overwrite_wplink', 99 );
}
}
/**
* Register styles and scripts.
*/
public function register() {
$js = rank_math()->plugin_url() . 'assets/admin/js/';
$css = rank_math()->plugin_url() . 'assets/admin/css/';
$vendor = rank_math()->plugin_url() . 'assets/vendor/';
// Styles.
wp_register_style( self::PREFIX . 'common', $css . 'common.css', null, rank_math()->version );
wp_register_style( self::PREFIX . 'cmb2', $css . 'cmb2.css', null, rank_math()->version );
wp_register_style( self::PREFIX . 'dashboard', $css . 'dashboard.css', [ 'rank-math-common', 'wp-components' ], rank_math()->version );
wp_register_style( self::PREFIX . 'dashboard-widget', $css . 'dashboard-widget.css', null, rank_math()->version );
// Scripts.
wp_register_script( self::PREFIX . 'common', $js . 'common.js', [ 'jquery', 'wp-i18n', 'lodash' ], rank_math()->version, true );
wp_register_script( self::PREFIX . 'dashboard', $js . 'dashboard.js', [ 'jquery', 'clipboard', 'lodash', 'wp-components', 'wp-element', 'rank-math-components' ], rank_math()->version, true );
wp_register_script( self::PREFIX . 'components', $js . 'components.js', [ 'lodash', 'wp-components', 'wp-element', 'wp-api-fetch' ], rank_math()->version, true );
// Select2.
wp_register_style( 'select2-rm', $vendor . 'select2/select2.min.css', null, '4.0.6-rc.1' );
wp_register_script( 'select2-rm', $vendor . 'select2/select2.min.js', null, '4.0.6-rc.1', true );
// Inline script for core admin page Settings > Permalinks.
wp_register_script( self::PREFIX . 'core-permalink-settings', '' ); // phpcs:ignore
wp_add_inline_script( self::PREFIX . 'core-permalink-settings', $this->get_permalinks_inline_script() );
Helper::add_json(
'api',
[
'root' => esc_url_raw( get_rest_url() ),
'nonce' => ( wp_installing() && ! is_multisite() ) ? '' : wp_create_nonce( 'wp_rest' ),
]
);
Helper::add_json(
'keywordsApi',
[
'url' => 'https://api.rankmath.com/ltkw/v1/',
]
);
Helper::add_json(
'links',
KB::get_links()
);
Helper::add_json(
'validationl10n',
[
'regexErrorDefault' => __( 'Please use the correct format.', 'seo-by-rank-math' ),
'requiredErrorDefault' => __( 'This field is required.', 'seo-by-rank-math' ),
'emailErrorDefault' => __( 'Please enter a valid email address.', 'seo-by-rank-math' ),
'urlErrorDefault' => __( 'Please enter a valid URL.', 'seo-by-rank-math' ),
]
);
Helper::add_json( 'capitalizeTitle', Helper::get_settings( 'titles.capitalize_titles' ) );
Helper::add_json( 'isConsoleConnected', Console::is_console_connected() );
Helper::add_json( 'isAnalyticsConnected', Analytics::is_analytics_connected() );
Helper::add_json( 'isUrlInspectionEnabled', Url_Inspection::is_enabled() );
/**
* Allow other plugins to register/deregister admin styles or scripts after plugin assets.
*/
$this->do_action( 'admin/register_scripts' );
}
/**
* Enqueue styles and scripts.
*/
public function enqueue() {
$screen = get_current_screen();
if ( 'dashboard' === $screen->id ) {
wp_enqueue_style( self::PREFIX . 'dashboard-widget' );
wp_enqueue_script( self::PREFIX . 'dashboard' );
}
$rank_math_pages = $this->do_filter(
'admin_pages',
[
'toplevel_page_rank-math',
'toplevel_page_rank-math-network',
'rank-math_page_rank-math-content-ai-page',
'rank-math_page_rank-math-analytics',
'rank-math_page_rank-math-role-manager',
'rank-math_page_rank-math-seo-analysis',
'rank-math_page_rank-math-status',
]
);
if (
in_array( $screen->id, $rank_math_pages, true ) ||
Str::starts_with( 'rank-math_page_rank-math-options-', $screen->id )
) {
Helper::add_json(
'dashboardHeader',
[
'dashboardUrl' => esc_url( Helper::get_admin_url() ),
'proBadge' => $this->do_filter( 'pro_badge', '' ),
]
);
}
// Our screens only.
if ( ! in_array( $screen->taxonomy, Helper::get_allowed_taxonomies(), true ) && ! in_array( $screen->id, $this->get_admin_screen_ids(), true ) ) {
return;
}
// Add thank you.
$this->filter( 'admin_footer_text', 'admin_footer_text' );
/**
* Allow other plugins to enqueue/dequeue admin styles or scripts after plugin assets.
*/
$this->do_action( 'admin/enqueue_scripts' );
}
/**
* Add footer credit on admin pages.
*
* @param string $text Default text for admin footer.
* @return string
*/
public function admin_footer_text( $text ) {
/* translators: plugin url */
return Helper::is_whitelabel() ? $text : sprintf( wp_kses_post( __( 'Thank you for using <a href="%s" target="_blank">Rank Math</a>', 'seo-by-rank-math' ) ), KB::get( 'seo-suite', 'Admin Footer Text' ) );
}
/**
* Overwrite wplink script file.
* Rank Math adds new options in the link popup when editing a post.
*/
public function overwrite_wplink() {
wp_deregister_script( 'wplink' );
wp_register_script( 'wplink', rank_math()->plugin_url() . 'assets/admin/js/wplink.js', [ 'jquery', 'wp-a11y' ], rank_math()->version, true );
wp_localize_script(
'wplink',
'wpLinkL10n',
[
'title' => esc_html__( 'Insert/edit link', 'seo-by-rank-math' ),
'update' => esc_html__( 'Update', 'seo-by-rank-math' ),
'save' => esc_html__( 'Add Link', 'seo-by-rank-math' ),
'noTitle' => esc_html__( '(no title)', 'seo-by-rank-math' ),
'noMatchesFound' => esc_html__( 'No matches found.', 'seo-by-rank-math' ),
'linkSelected' => esc_html__( 'Link selected.', 'seo-by-rank-math' ),
'linkInserted' => esc_html__( 'Link inserted.', 'seo-by-rank-math' ),
'relCheckbox' => __( 'Add <code>rel="nofollow"</code>', 'seo-by-rank-math' ),
'sponsoredCheckbox' => __( 'Add <code>rel="sponsored"</code>', 'seo-by-rank-math' ),
'linkTitle' => esc_html__( 'Link Title', 'seo-by-rank-math' ),
]
);
}
/**
* Enqueues styles.
*
* @param string $style Name of the style.
*/
public function enqueue_style( $style ) {
wp_enqueue_style( self::PREFIX . $style );
}
/**
* Enqueues scripts.
*
* @param string $script Name of the script.
*/
public function enqueue_script( $script ) {
wp_enqueue_script( self::PREFIX . $script );
}
/**
* Get admin screen ids.
*
* @return array
*/
private function get_admin_screen_ids() {
$pages = [
'toplevel_page_rank-math',
'rank-math_page_rank-math-role-manager',
'rank-math_page_rank-math-seo-analysis',
'rank-math_page_rank-math-links-page',
'rank-math_page_rank-math-ai-visibility',
'rank-math_page_rank-math-404-monitor',
'rank-math_page_rank-math-redirections',
'rank-math_page_rank-math-link-builder',
'rank-math_page_rank-math-analytics',
'rank-math_page_rank-math-import-export',
'rank-math_page_rank-math-help',
'user-edit',
'profile',
'rank_math_schema',
];
return array_merge( $pages, Helper::get_allowed_post_types() );
}
/**
* Inline script to warn the user about the risks of changing the permalinks on a live site.
*
* @return string
*/
public function get_permalinks_inline_script() {
// Don't add the script if site is set to noindex.
if ( ! get_option( 'blog_public' ) ) {
return '';
}
return "jQuery( window ).load( function() {
var noticeShown = false;
var showNotice = function() {
if ( noticeShown ) {
return true;
}
jQuery( '.rank-math-notice-permalinks-warning' ).removeClass( 'hidden' ).insertBefore( 'p.submit' );
noticeShown = true;
return true;
}
jQuery( '.available-structure-tags button' ).on( 'click', showNotice );
jQuery( 'input[type=text], input[type=radio]' ).on( 'focus change', showNotice );
} );";
}
}
@@ -0,0 +1,201 @@
<?php
/**
* The admin post columns functionality.
*
* @since 1.0.212
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Helper;
use RankMath\Helpers\Param;
use RankMath\Helpers\Url;
use RankMath\Runner;
use RankMath\Traits\Hooker;
use RankMath\Admin\Admin_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Post_Columns class.
*/
class Bulk_Actions implements Runner {
use Hooker;
/**
* SEO data.
*
* @var array
*/
private $data = [];
/**
* Register hooks.
*/
public function hooks() {
$this->action( 'current_screen', 'init' );
}
/**
* Initialize.
*/
public function init() {
if ( ! Helper::has_cap( 'onpage_general' ) || ! $this->can_add() ) {
return;
}
$this->register_post_columns();
$this->action( 'admin_enqueue_scripts', 'enqueue' );
}
/**
* Register post column hooks.
*/
private function register_post_columns() {
$post_types = Helper::get_allowed_post_types();
foreach ( $post_types as $post_type ) {
$this->filter( "bulk_actions-edit-{$post_type}", 'post_bulk_actions' );
$this->filter( "handle_bulk_actions-edit-{$post_type}", 'handle_bulk_actions', 10, 3 );
}
$taxonomies = Helper::get_accessible_taxonomies();
unset( $taxonomies['post_format'] );
$taxonomies = wp_list_pluck( $taxonomies, 'label', 'name' );
foreach ( $taxonomies as $taxonomy => $label ) {
$this->filter( "bulk_actions-edit-{$taxonomy}", 'post_bulk_actions' );
}
}
/**
* Add bulk actions for applicable posts, pages, CPTs.
*
* @param array $actions Actions.
* @return array New actions.
*/
public function post_bulk_actions( $actions ) {
$new_actions = [ 'rank_math_options' => __( '&#8595; Rank Math', 'seo-by-rank-math' ) ];
if ( Helper::has_cap( 'onpage_advanced' ) ) {
$new_actions['rank_math_bulk_robots_noindex'] = __( 'Set to noindex', 'seo-by-rank-math' );
$new_actions['rank_math_bulk_robots_index'] = __( 'Set to index', 'seo-by-rank-math' );
$new_actions['rank_math_bulk_robots_nofollow'] = __( 'Set to nofollow', 'seo-by-rank-math' );
$new_actions['rank_math_bulk_robots_follow'] = __( 'Set to follow', 'seo-by-rank-math' );
$new_actions['rank_math_bulk_remove_canonical'] = __( 'Remove custom canonical URL', 'seo-by-rank-math' );
if ( Helper::is_module_active( 'redirections' ) && Helper::has_cap( 'redirections' ) ) {
$new_actions['rank_math_bulk_redirect'] = __( 'Redirect', 'seo-by-rank-math' );
$new_actions['rank_math_bulk_stop_redirect'] = __( 'Remove redirection', 'seo-by-rank-math' );
}
}
if ( Helper::is_module_active( 'rich-snippet' ) && Helper::has_cap( 'onpage_snippet' ) ) {
$new_actions['rank_math_bulk_schema_none'] = __( 'Set Schema: None', 'seo-by-rank-math' );
$post_type = Param::get( 'post_type', get_post_type() );
$post_type_default = Helper::get_settings( 'titles.pt_' . $post_type . '_default_rich_snippet' );
if ( ( class_exists( 'WooCommerce' ) && 'product' === $post_type ) || ( class_exists( 'Easy_Digital_Downloads' ) && 'download' === $post_type ) ) {
$post_type_default = 'download' === $post_type ? esc_html__( 'EDD Product', 'seo-by-rank-math' ) : esc_html__( 'WC Product', 'seo-by-rank-math' );
}
if ( $post_type_default ) {
// Translators: placeholder is the default Schema type setting.
$new_actions['rank_math_bulk_schema_default'] = sprintf( __( 'Set Schema: Default (%s)', 'seo-by-rank-math' ), $post_type_default );
}
}
if ( Helper::has_cap( 'onpage_general' ) && Helper::should_determine_search_intent() ) {
$new_actions['rank_math_bulk_determine_search_intent'] = __( 'Determine Search Intent', 'seo-by-rank-math' );
}
if ( is_array( $actions ) && count( $new_actions ) > 1 ) {
return array_merge( $actions, $new_actions );
}
return $actions;
}
/**
* Handle bulk actions for applicable posts, pages, CPTs.
*
* @param string $redirect Redirect URL.
* @param string $doaction Performed action.
* @param array $object_ids Post IDs.
*
* @return string New redirect URL.
*/
public function handle_bulk_actions( $redirect, $doaction, $object_ids ) {
if (
$doaction === 'rank_math_bulk_determine_search_intent' &&
(
defined( 'RANK_MATH_PRO_VERSION' ) &&
version_compare( RANK_MATH_PRO_VERSION, '3.0.83-beta', '<' )
)
) {
Helper::add_notification(
esc_html__( 'Your current plugin version does not support this feature. Please update Rank Math PRO to version 3.0.83 or later to unlock full functionality.', 'seo-by-rank-math' ),
[
'type' => 'error',
'id' => 'rank_math_search_intent_error',
'classes' => 'rank-math-notice',
]
);
}
return $redirect;
}
/**
* Enqueue styles and scripts.
*/
public function enqueue() {
$screen = get_current_screen();
wp_enqueue_style( 'rank-math-post-bulk-edit', rank_math()->plugin_url() . 'assets/admin/css/post-list.css', [ 'wp-components' ], rank_math()->version );
if ( Admin_Helper::is_term_listing() ) {
$allow_editing = Helper::get_settings( 'titles.tax_' . $screen->taxonomy . '_bulk_editing', false );
} else {
$allow_editing = Helper::get_settings( 'titles.pt_' . $screen->post_type . '_bulk_editing', true );
}
if ( ! $allow_editing || 'readonly' === $allow_editing ) {
return;
}
wp_enqueue_script( 'rank-math-post-bulk-edit', rank_math()->plugin_url() . 'assets/admin/js/post-list.js', [ 'lodash', 'wp-element', 'wp-components' ], rank_math()->version, true );
Helper::add_json(
'contentAI',
[
'isUserRegistered' => Helper::is_site_connected(),
'credits' => Helper::get_content_ai_credits(),
'plan' => Helper::get_content_ai_plan(),
]
);
Helper::add_json( 'isProActive', defined( 'RANK_MATH_PRO_FILE' ) );
Helper::add_json( 'connectSiteUrl', Admin_Helper::get_activate_url( Url::get_current_url() ) );
}
/**
* Whether to add Bulk actions on the page.
*/
private function can_add() {
global $pagenow;
if ( 'edit-tags.php' === $pagenow ) {
return Helper::get_settings( 'titles.tax_' . Param::get( 'taxonomy' ) . '_add_meta_box' );
}
if ( Admin_Helper::is_post_list() || Admin_Helper::is_media_library() ) {
$screen = get_current_screen();
$allowed_post_types = Helper::get_allowed_post_types();
$allowed_post_types[] = 'attachment';
return in_array( $screen->post_type, $allowed_post_types, true );
}
return false;
}
}
@@ -0,0 +1,334 @@
<?php
/**
* The CMB2 fields for the plugin.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Runner;
use RankMath\Helpers\Str;
use RankMath\Traits\Hooker;
use RankMath\Admin\Admin_Helper;
defined( 'ABSPATH' ) || exit;
/**
* CMB2_Fields class.
*
* @codeCoverageIgnore
*/
class CMB2_Fields implements Runner {
use Hooker;
/**
* Register hooks.
*/
public function hooks() {
if ( ! has_action( 'cmb2_render_switch' ) ) {
$this->action( 'cmb2_render_switch', 'render_switch', 10, 5 );
}
if ( ! has_action( 'cmb2_render_notice' ) ) {
$this->action( 'cmb2_render_notice', 'render_notice' );
}
if ( ! has_action( 'cmb2_render_address' ) ) {
$this->action( 'cmb2_render_address', 'render_address', 10, 5 );
}
if ( ! has_action( 'cmb2_render_advanced_robots' ) ) {
$this->action( 'cmb2_render_advanced_robots', 'render_advanced_robots', 10, 5 );
}
if ( ! has_action( 'cmb2_render_toggle' ) ) {
$this->action( 'cmb2_render_toggle', 'render_toggle', 10, 5 );
}
$this->filter( 'cmb2_sanitize_toggle', 'sanitize_toggle', 10, 2 );
$this->filter( 'cmb2_field_arguments_raw', 'default_value', 10, 2 );
}
/**
* Set a default value in default_cb to prevent the callback function from executing on the site.
*
* @see https://github.com/CMB2/CMB2/issues/750
*
* @param array $args The field arguments.
* @param object $cmb2 The CMB2 object.
*/
public function default_value( $args, $cmb2 ) {
if (
! Str::starts_with( 'rank-math', trim( $cmb2->cmb_id ) ) ||
! isset( $args['default'] ) ||
! is_callable( $args['default'] )
) {
return $args;
}
$args['default_cb'] = function () use ( $args ) {
return $args['default'];
};
$args['default'] = null;
return $args;
}
/**
* Sanitize toggle field.
*
* @param string $override_value Sanitization override value to return.
* @param string $value The field value.
*/
public function sanitize_toggle( $override_value, $value ) {
return is_null( $value ) ? 'off' : $value;
}
/**
* Render toggle field.
*
* @param array $field The passed in `CMB2_Field` object.
* @param mixed $escaped_value The value of this field escaped
* It defaults to `sanitize_text_field`.
* If you need the unescaped value, you can access it
* via `$field->value()`.
* @param int $object_id The ID of the current object.
* @param string $object_type The type of object you are working with.
* Most commonly, `post` (this applies to all post-types),
* but could also be `comment`, `user` or `options-page`.
* @param object $field_type_object This `CMB2_Types` object.
*/
public function render_toggle( $field, $escaped_value, $object_id, $object_type, $field_type_object ) {
$field_name = $field->_name();
$active_value = ! empty( $field->args( 'active_value' ) ) ? $field->args( 'active_value' ) : 'on';
$escaped_value = ! empty( $field->args( 'force_enable' ) ) ? 'on' : $escaped_value;
$args = [
'type' => 'checkbox',
'id' => $field_name,
'name' => $field_name,
'desc' => '',
'value' => $active_value,
'disabled' => isset( $field->args['disabled'] ) ? $field->args['disabled'] : false,
];
if ( $escaped_value === $active_value ) {
$args['checked'] = 'checked';
}
echo '<label class="cmb2-toggle">';
echo $field_type_object->input( $args ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CMB2 handles escaping.
echo '<span class="cmb2-slider">';
echo '<svg width="3" height="8" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2 6" class="toggle_on" role="img" aria-hidden="true" focusable="false"><path d="M0 0h2v6H0z"></path></svg>';
echo '<svg width="8" height="8" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 6 6" class="toggle_off" role="img" aria-hidden="true" focusable="false"><path d="M3 1.5c.8 0 1.5.7 1.5 1.5S3.8 4.5 3 4.5 1.5 3.8 1.5 3 2.2 1.5 3 1.5M3 0C1.3 0 0 1.3 0 3s1.3 3 3 3 3-1.3 3-3-1.3-3-3-3z"></path></svg>';
echo '</span>';
echo '</label>';
$field_type_object->_desc( true, true );
}
/**
* Render switch field.
*
* @param array $field The passed in `CMB2_Field` object.
* @param mixed $escaped_value The value of this field escaped
* It defaults to `sanitize_text_field`.
* If you need the unescaped value, you can access it
* via `$field->value()`.
* @param int $object_id The ID of the current object.
* @param string $object_type The type of object you are working with.
* Most commonly, `post` (this applies to all post-types),
* but could also be `comment`, `user` or `options-page`.
* @param object $field_type_object This `CMB2_Types` object.
*/
public function render_switch( $field, $escaped_value, $object_id, $object_type, $field_type_object ) {
if ( empty( $field->args['options'] ) ) {
$field->args['options'] = [
'off' => esc_html( $field->get_string( 'off', __( 'Off', 'seo-by-rank-math' ) ) ),
'on' => esc_html( $field->get_string( 'on', __( 'On', 'seo-by-rank-math' ) ) ),
];
}
$field->set_options();
echo $field_type_object->radio_inline(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CMB2 handles escaping.
}
/**
* Render notices
*
* @param object $field The passed in `CMB2_Field` object.
*/
public function render_notice( $field ) {
$hash = [
'error' => 'notice notice-alt notice-error error inline rank-math-notice',
'info' => 'notice notice-alt notice-info info inline rank-math-notice',
'warning' => 'notice notice-alt notice-warning warning inline rank-math-notice',
];
echo '<div class="' . esc_attr( $hash[ $field->args( 'what' ) ] ) . '"><p>' . $field->args( 'content' ) . '</p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CMB2 handles escaping.
}
/**
* Render address field.
*
* @param object $field The passed in `CMB2_Field` object.
* @param mixed $escaped_value The value of this field escaped
* It defaults to `sanitize_text_field`.
* If you need the unescaped value, you can access it
* via `$field->value()`.
* @param int $object_id The ID of the current object.
* @param string $object_type The type of object you are working with.
* Most commonly, `post` (this applies to all post-types),
* but could also be `comment`, `user` or `options-page`.
* @param object $field_type_object This `CMB2_Types` object.
*/
public function render_address( $field, $escaped_value, $object_id, $object_type, $field_type_object ) {
// Make sure we assign each part of the value we need.
$value = wp_parse_args(
$escaped_value,
[
'streetAddress' => '',
'addressLocality' => '',
'addressRegion' => '',
'postalCode' => '',
'addressCountry' => '',
]
);
$strings = [
'streetAddress' => 'Street Address',
'addressLocality' => 'Locality',
'addressRegion' => 'Region',
'postalCode' => 'Postal Code',
'addressCountry' => '2-letter Country Code (ISO 3166-1)',
];
foreach ( array_keys( $value ) as $id ) :
$field_input = $field_type_object->input(
[
'name' => $field_type_object->_name( '[' . $id . ']' ),
'id' => $field_type_object->_id( '_' . $id ),
'value' => $value[ $id ],
'placeholder' => esc_html( $field->get_string( $id . '_text', $strings[ $id ] ) ),
]
);
echo '<div class="cmb-address-field">' . $field_input . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CMB2 handles escaping.
endforeach;
}
/**
* Render Advanced Robots fields.
*
* @param object $field The passed in `CMB2_Field` object.
* @param mixed $escaped_value The value of this field escaped
* It defaults to `sanitize_text_field`.
* If you need the unescaped value, you can access it
* via `$field->value()`.
* @param int $object_id The ID of the current object.
* @param string $object_type The type of object you are working with.
* Most commonly, `post` (this applies to all post-types),
* but could also be `comment`, `user` or `options-page`.
* @param object $field_type_object This `CMB2_Types` object.
*/
public function render_advanced_robots( $field, $escaped_value, $object_id, $object_type, $field_type_object ) {
// Make sure we assign each part of the value we need.
$values = wp_parse_args(
$escaped_value,
[
'max-snippet' => -1,
'max-video-preview' => -1,
'max-image-preview' => 'large',
]
);
$strings = [
'max-snippet' => __( 'Snippet', 'seo-by-rank-math' ) . Admin_Helper::get_tooltip( esc_html__( 'Specify a maximum text-length, in characters, of a snippet for your page.', 'seo-by-rank-math' ) ),
'max-video-preview' => __( 'Video Preview', 'seo-by-rank-math' ) . Admin_Helper::get_tooltip( esc_html__( 'Specify a maximum duration in seconds of an animated video preview.', 'seo-by-rank-math' ) ),
'max-image-preview' => __( 'Image Preview', 'seo-by-rank-math' ) . Admin_Helper::get_tooltip( esc_html__( 'Specify a maximum size of image preview to be shown for images on this page.', 'seo-by-rank-math' ) ),
];
echo '<ul class="cmb-advanced-robots-list no-select-all cmb2-list cmb-rank-math-advanced-robots-field">';
foreach ( $values as $id => $value ) :
$value = isset( $escaped_value[ $id ] ) ? $escaped_value[ $id ] : $value;
echo '<li>';
echo '<label for="' . esc_attr( $field_type_object->_id( '_' . $id . '_name' ) ) . '">';
echo $this->get_advanced_robots_field( 'checkbox', $field_type_object, $id, $value, $escaped_value ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CMB2 handles escaping.
echo wp_kses_post( $field->get_string( $id . '_text', $strings[ $id ] ) ) . '</label>';
if ( 'max-image-preview' === $id ) {
echo $this->get_advanced_robots_field( 'select', $field_type_object, $id, $value, $escaped_value ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CMB2 handles escaping.
}
if ( 'max-image-preview' !== $id ) {
echo $this->get_advanced_robots_field( 'input', $field_type_object, $id, $value, $escaped_value ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CMB2 handles escaping.
}
echo '</li>';
endforeach;
echo '</ul>';
}
/**
* Get the field markup for the advanced robots field.
*
* @param string $field_type The type of field.
* @param object $field_type_object The CMB2_Types object.
* @param string $id The field id.
* @param string $value The field value.
* @param string $escaped_value The escaped field value.
*
* @return string The field markup.
*/
private function get_advanced_robots_field( $field_type, $field_type_object, $id, $value, $escaped_value ) {
$props = [
'name' => $field_type_object->_name( "[{$id}][length]" ),
'id' => $field_type_object->_id( '_' . $id . '_name' ),
];
switch ( $field_type ) {
case 'checkbox':
$props['name'] = $field_type_object->_name( "[{$id}][enable]" );
$props['value'] = true;
$props['checked'] = ! empty( $escaped_value[ $id ] ) || empty( $escaped_value ) ? 'checked' : false;
break;
case 'select':
$props['options'] = $this->get_image_sizes( $value );
break;
case 'input':
$props['value'] = $value ? $value : -1;
$props['type'] = 'number';
$props['min'] = -1;
break;
}
return $field_type_object->$field_type( $props );
}
/**
* Get Image sizes.
*
* @param string $size The selected image size.
* @return string $options The image sizes.
*/
private function get_image_sizes( $size = 'large' ) {
$values = [
'large' => __( 'Large', 'seo-by-rank-math' ),
'standard' => __( 'Standard', 'seo-by-rank-math' ),
'none' => __( 'None', 'seo-by-rank-math' ),
];
$options = '';
foreach ( $values as $data => $label ) {
$options .= '<option value="' . $data . '" ' . selected( $size, $data, false ) . ' >' . $label . '</option>';
}
return $options;
}
}
@@ -0,0 +1,496 @@
<?php
/**
* The option page functionality of the plugin.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use WP_Http;
use RankMath\KB;
use RankMath\CMB2;
use RankMath\Helper;
use RankMath\Traits\Hooker;
use RankMath\Helpers\Str;
use RankMath\Helpers\Param;
defined( 'ABSPATH' ) || exit;
/**
* CMB2_Options class.
*/
class CMB2_Options {
use Hooker;
/**
* Page title.
*
* @var string
*/
public $title = 'Settings';
/**
* Menu title.
*
* @var string
*/
public $menu_title = 'Settings';
/**
* Hold tabs for page.
*
* @var array
*/
public $tabs = [];
/**
* Hold folder name for tab files.
*
* @var string
*/
public $folder = '';
/**
* Menu Position.
*
* @var int
*/
public $position = 10;
/**
* The capability required for this menu to be displayed to the user.
*
* @var string
*/
public $capability = 'manage_options';
/**
* CMB2 option page id.
*
* @var string
*/
private $cmb_id = null;
/**
* Options key.
*
* @var string
*/
public $key = '';
/**
* The Constructor
*
* @param array $config Array of configuration.
*/
public function __construct( $config ) {
$this->config( $config );
$this->cmb_id = $this->key . '_options';
$this->action( 'cmb2_admin_init', 'register_option_page', $this->position );
$this->action( 'admin_post_' . $this->key, 'reset_options', 2 );
if ( true === empty( get_option( $this->key ) ) ) {
$this->action( 'cmb2_init_hookup_' . $this->cmb_id, 'set_defaults', 11 );
}
if ( ! $this->is_current_page() ) {
return;
}
$this->action( 'admin_enqueue_scripts', 'enqueue' );
$this->action( 'admin_body_class', 'body_class' );
// Check for fields and act accordingly.
$this->action( 'cmb2_save_options-page_fields_rank-math-options-general_options', 'check_updated_fields', 25, 2 );
$this->action( 'cmb2_save_options-page_fields_rank-math-options-titles_options', 'check_updated_fields', 25, 2 );
}
/**
* Create cmb2 box.
*
* @return CMB2
*/
private function create_cmb2() {
return new_cmb2_box(
[
'id' => $this->cmb_id,
'title' => $this->title,
'menu_title' => $this->menu_title,
'capability' => $this->capability,
'object_types' => [ 'options-page' ],
'option_key' => $this->key,
'parent_slug' => 'rank-math',
'cmb_styles' => false,
'display_cb' => [ $this, 'display' ],
]
);
}
/**
* Create option object and add settings.
*/
public function register_option_page() {
$cmb = $this->create_cmb2();
$tabs = $this->get_tabs();
$cmb->add_field(
[
'id' => 'setting-panel-container-' . $this->cmb_id,
'type' => 'tab_container_open',
'classes' => 'before-header',
'tabs' => $tabs,
]
);
foreach ( $tabs as $id => $tab ) {
$located = $this->locate_file( $id, $tab );
if ( false === $located ) {
continue;
}
$cmb->add_field(
[
'name' => esc_html__( 'Panel', 'seo-by-rank-math' ),
'id' => 'setting-panel-' . $id,
'type' => 'tab',
'open' => true,
'classes' => isset( $tab['classes'] ) ? $tab['classes'] : '',
]
);
$cmb->add_field(
[
'id' => $id . '_section_title',
'type' => 'title',
'name' => isset( $tab['page_title'] ) ? $tab['page_title'] : ( isset( $tab['title'] ) ? $tab['title'] : '' ),
'desc' => isset( $tab['desc'] ) ? $tab['desc'] : '',
'after' => isset( $tab['after'] ) ? $tab['after'] : '',
'classes' => 'tab-header',
'after_row' => isset( $tab['after_row'] ) ? $tab['after_row'] : '',
]
);
include $located;
$this->do_action( "admin/settings/{$id}", $cmb, $tab );
$cmb->add_field(
[
'id' => 'setting-panel-' . $id . '-close',
'type' => 'tab',
]
);
}
$cmb->add_field(
[
'id' => 'setting-panel-container-close-' . $this->cmb_id,
'type' => 'tab_container_close',
]
);
CMB2::pre_init( $cmb );
}
/**
* Set the default values if not set.
*
* @param CMB2 $cmb The CMB2 object to hookup.
*/
public function set_defaults( $cmb ) {
foreach ( $cmb->prop( 'fields' ) as $id => $field_args ) {
$field = $cmb->get_field( $id );
if ( isset( $field_args['default'] ) || isset( $field_args['default_cb'] ) ) {
$defaults[ $id ] = $field->get_default();
}
}
// Save Defaults if any.
if ( ! empty( $defaults ) ) {
add_option( $this->key, $defaults );
}
}
/**
* Reset options.
*/
public function reset_options() {
if ( ! check_admin_referer( 'rank-math-reset-options' ) || ! current_user_can( 'manage_options' ) ) {
return false;
}
$url = wp_get_referer();
if ( ! $url ) {
$url = admin_url();
}
if ( filter_has_var( INPUT_POST, 'reset-cmb' ) && Param::post( 'action' ) === $this->key ) {
delete_option( $this->key );
Helper::redirect( esc_url_raw( $url ), WP_Http::SEE_OTHER );
exit;
}
}
/**
* Enqueue styles and scripts.
*/
public function enqueue() {
$screen = get_current_screen();
if ( ! Str::contains( $this->key, $screen->id ) ) {
return;
}
\CMB2_Hookup::enqueue_cmb_css();
rank_math()->variables->setup_json();
wp_enqueue_style( 'rank-math-options', rank_math()->plugin_url() . 'assets/admin/css/option-panel.css', [ 'select2-rm', 'rank-math-common', 'rank-math-cmb2' ], rank_math()->version );
wp_enqueue_script( 'rank-math-options', rank_math()->plugin_url() . 'assets/admin/js/option-panel.js', [ 'underscore', 'select2-rm', 'lodash', 'rank-math-common', 'wp-api-fetch' ], rank_math()->version, true );
// Add thank you.
Helper::add_json( 'indexUrl', rank_math()->plugin_url() . 'assets/admin/js/search-index/' );
Helper::add_json( 'optionPage', str_replace( 'rank-math-options-', '', $this->key ) );
}
/**
* Add classes to <body> of WordPress admin.
*
* @param string $classes List of CSS classes.
* @return string
*/
public function body_class( $classes = '' ) {
$mode = Helper::is_advanced_mode() ? 'advanced' : 'basic';
return $classes . ' rank-math-page rank-math-mode-' . $mode;
}
/**
* Display Setting on a page.
*
* @param CMB2_Options $machine Current CMB2 box object.
*/
public function display( $machine ) {
$cmb = $machine->cmb;
// Header.
rank_math()->admin->display_admin_header();
?>
<?php if ( ! defined( 'RANK_MATH_PRO_FILE' ) ) : ?>
<div class="rank-math-unlock-pro-notice" id="rank-math-unlock-pro-notice">
<a href="<?php KB::the( 'pro', 'Unlock PRO Options Panel Notice' ); ?>" target="_blank" class="pro-link">
<p>
<?php esc_html_e( 'Take your SEO to the Next Level!', 'seo-by-rank-math' ); ?>
<strong><?php esc_html_e( 'Get Rank Math PRO!', 'seo-by-rank-math' ); ?></strong>
<span><?php esc_html_e( 'Click here to see all the exciting features.', 'seo-by-rank-math' ); ?></span>
</p>
<div class="close-notice">
<span class="dashicons dashicons-dismiss"></span>
</div>
</a>
</div>
<?php endif; ?>
<div class="wrap rank-math-wrap rank-math-wrap-settings">
<span class="wp-header-end"></span>
<form class="cmb-form" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="POST" id="<?php echo esc_attr( $cmb->cmb_id ); ?>" enctype="multipart/form-data" encoding="multipart/form-data">
<input type="hidden" name="action" value="<?php echo esc_attr( $machine->option_key ); ?>">
<?php $machine->options_page_metabox(); ?>
<footer class="form-footer rank-math-ui settings-footer wp-clearfix">
<?php wp_nonce_field( 'rank-math-reset-options' ); ?>
<input type="submit" name="submit-cmb" id="submit-cmb" title="<?php echo esc_html__( 'Ctrl/Cmd + Enter', 'seo-by-rank-math' ); ?>" class="button button-primary save-options" value="<?php esc_attr_e( 'Save Changes', 'seo-by-rank-math' ); ?>">
<input type="submit" name="reset-cmb" id="rank-math-reset-cmb" value="<?php esc_attr_e( 'Reset Options', 'seo-by-rank-math' ); ?>" class="button button-secondary reset-options alignleft">
</footer>
</form>
</div>
<?php
}
/**
* Check if we are on the correct page.
*
* @return bool
*/
public function is_current_page() {
return Param::request( 'page' ) === $this->key || Param::request( 'action' ) === $this->key;
}
/**
* Check if certain fields got updated.
*
* @param int $object_id The ID of the current object.
* @param array $updated Array of field ids that were updated.
* Will only include field ids that had values change.
*/
public function check_updated_fields( $object_id, $updated ) {
/**
* Filter: Allow developers to add option fields which will flush the rewrite rules when updated.
*
* @param array $flush_fields Array of field IDs for which we need to flush.
*/
$flush_fields = $this->do_filter(
'flush_fields',
[
'strip_category_base',
'disable_author_archives',
'url_author_base',
'attachment_redirect_urls',
'attachment_redirect_default',
'nofollow_external_links',
'nofollow_image_links',
'nofollow_domains',
'nofollow_exclude_domains',
'new_window_external_links',
'redirections_header_code',
'redirections_post_redirect',
'redirections_debug',
]
);
foreach ( $flush_fields as $field_id ) {
if ( in_array( $field_id, $updated, true ) ) {
Helper::schedule_flush_rewrite();
break;
}
}
$this->maybe_update_htaccess();
}
/**
* Update .htaccess.
*/
private function maybe_update_htaccess() {
if ( empty( Param::post( 'htaccess_accept_changes' ) ) ) {
return;
}
if ( ! is_super_admin() || ! Helper::has_cap( 'general' ) || ! Helper::has_cap( 'edit_htaccess' ) ) {
Helper::add_notification(
esc_html__( 'You do not have permission to edit the .htaccess file.', 'seo-by-rank-math' ),
[ 'type' => 'error' ]
);
return;
}
if ( ! Helper::is_edit_allowed() ) {
Helper::add_notification(
esc_html__( 'You do not have permission to edit the .htaccess file.', 'seo-by-rank-math' ),
[ 'type' => 'error' ]
);
return;
}
// phpcs:ignore= WordPress.Security.ValidatedSanitizedInput, WordPress.Security.NonceVerification -- Writing to .htaccess file and escaping for HTML will break functionality & CMB2 package handles the nonce verification
$content = isset( $_POST['htaccess_content'] ) ? wp_unslash( $_POST['htaccess_content'] ) : '';
if ( empty( $content ) ) {
return;
}
if ( ! $this->do_htaccess_backup() ) {
Helper::add_notification(
esc_html__( 'Failed to backup .htaccess file. Please check file permissions.', 'seo-by-rank-math' ),
[ 'type' => 'error' ]
);
return;
}
if ( ! $this->do_htaccess_update( $content ) ) {
Helper::add_notification(
esc_html__( 'Failed to update .htaccess file. Please check file permissions.', 'seo-by-rank-math' ),
[ 'type' => 'error' ]
);
return;
}
Helper::add_notification( esc_html__( '.htaccess file updated successfully.', 'seo-by-rank-math' ) );
}
/**
* Create htaccess backup.
*
* @return bool
*/
private function do_htaccess_backup() {
if ( ! Helper::is_filesystem_direct() ) {
return false;
}
$wp_filesystem = Helper::get_filesystem();
$path = get_home_path();
$file = $path . '.htaccess';
if ( ! $wp_filesystem->is_writable( $path ) || ! $wp_filesystem->exists( $file ) ) {
return false;
}
$backup = $path . uniqid( '.htaccess_back_' );
return $wp_filesystem->copy( $file, $backup, true );
}
/**
* Update htaccess file.
*
* @param string $content Htaccess content.
* @return string|bool
*/
private function do_htaccess_update( $content ) {
if ( empty( $content ) || ! Helper::is_filesystem_direct() ) {
return false;
}
$wp_filesystem = Helper::get_filesystem();
$htaccess_file = get_home_path() . '.htaccess';
return ! $wp_filesystem->is_writable( $htaccess_file ) ? false : $wp_filesystem->put_contents( $htaccess_file, $content );
}
/**
* Get setting tabs.
*
* @return array
*/
private function get_tabs() {
$filter = str_replace( '-', '_', str_replace( 'rank-math-', '', $this->key ) );
/**
* Allow developers to add new tabs into option panel.
*
* The dynamic part of hook is, page name without 'rank-math-' prefix.
*
* @param array $tabs
*/
return $this->do_filter( "admin/options/{$filter}_tabs", $this->tabs );
}
/**
* Locate tab options file.
*
* @param string $id Tab id.
* @param array $tab Tab options.
* @return string|boolean
*/
private function locate_file( $id, $tab ) {
if ( isset( $tab['type'] ) && 'separator' === $tab['type'] ) {
return false;
}
$file = isset( $tab['file'] ) && ! empty( $tab['file'] ) ? $tab['file'] : rank_math()->includes_dir() . "settings/{$this->folder}/{$id}.php";
return file_exists( $file ) ? $file : false;
}
}
@@ -0,0 +1,224 @@
<?php
/**
* The Dashboard Widget of the plugin.
*
* @since 1.0.81
* @package RankMath
* @subpackage RankMath\Core
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath;
use RankMath\KB;
use RankMath\Helper;
use RankMath\Traits\Hooker;
defined( 'ABSPATH' ) || exit;
/**
* Dashboard_Widget class.
*
* @codeCoverageIgnore
*/
class Dashboard_Widget {
use Hooker;
/**
* Constructor.
*/
public function __construct() {
$this->action( 'wp_dashboard_setup', 'add_dashboard_widgets' );
$this->action( 'rank_math/dashboard/widget', 'dashboard_widget_feed', 98 );
$this->action( 'rank_math/dashboard/widget', 'dashboard_widget_footer', 99 );
}
/**
* Register dashboard widget.
*/
public function add_dashboard_widgets() {
// Early Bail if action is not registered for the dashboard widget hook.
if (
( ! Helper::is_module_active( '404-monitor' ) || ! Helper::has_cap( '404_monitor' ) ) &&
( ! Helper::is_module_active( 'redirections' ) || ! Helper::has_cap( 'redirections' ) ) &&
( ! Helper::is_module_active( 'analytics' ) || ! Helper::has_cap( 'analytics' ) )
) {
return;
}
$icon = '<span class="rank-math-icon"><svg viewBox="0 0 462.03 462.03" xmlns="http://www.w3.org/2000/svg" width="20"><g><path d="m462 234.84-76.17 3.43 13.43 21-127 81.18-126-52.93-146.26 60.97 10.14 24.34 136.1-56.71 128.57 54 138.69-88.61 13.43 21z"></path><path d="m54.1 312.78 92.18-38.41 4.49 1.89v-54.58h-96.67zm210.9-223.57v235.05l7.26 3 89.43-57.05v-181zm-105.44 190.79 96.67 40.62v-165.19h-96.67z"></path></g></svg></span>';
wp_add_dashboard_widget(
'rank_math_dashboard_widget',
$icon . esc_html__( 'Rank Math Overview', 'seo-by-rank-math' ),
[ $this, 'render_dashboard_widget' ],
null,
null,
'normal',
'high'
);
}
/**
* Render dashboard widget.
*/
public function render_dashboard_widget() {
echo '<div id="rank-math-dashboard-widget" class="rank-math-loading"></div>';
}
/**
* Add Feed data in the admin dashboard widget.
*/
public function dashboard_widget_feed() {
$posts = $this->get_feed();
?>
<h3 class="rank-math-blog-title"><?php esc_html_e( 'Latest Blog Posts from Rank Math', 'seo-by-rank-math' ); ?></h3>
<?php if ( empty( $posts ) ) : ?>
<p><?php esc_html_e( 'Error: the Rank Math blog feed could not be downloaded.', 'seo-by-rank-math' ); ?></p>
<?php
return;
endif;
echo '<ul class="rank-math-blog-list">';
$posts = $this->filter_posts( $posts );
$label = $this->get_item_label( $posts );
foreach ( $posts as $index => $post ) :
$link = $this->add_utm_params( $post['link'], $index );
?>
<li class="rank-math-blog-post">
<h4>
<?php if ( $label ) : ?>
<span class="rank-math-new-badge"><?php echo esc_html( $label ); ?></span>
<?php endif; ?>
<a target="_blank" href="<?php echo esc_url( $link ); ?>">
<?php echo esc_html( $post['title']['rendered'] ); ?>
</a>
</h4>
</li>
<?php
$label = '';
endforeach;
echo '</ul>';
}
/**
* Get label for first post.
*
* @param array $posts Posts.
*/
private function get_item_label( $posts ) {
$label = '';
if ( ! empty( $posts[0]['custom_label'] ) ) {
$label = $posts[0]['custom_label'];
}
$is_new = time() - strtotime( $posts[0]['date'] ) < 15 * DAY_IN_SECONDS;
if ( $is_new && empty( $label ) ) {
$label = esc_html__( 'NEW', 'seo-by-rank-math' );
}
return $label;
}
/**
* Filter posts by display condition.
*
* @param array $posts Posts.
*/
private function filter_posts( $posts ) {
$posts = array_filter(
$posts,
function ( $post ) {
if ( isset( $post['condition'] ) && 'is_free' === $post['condition'] && defined( 'RANK_MATH_PRO_FILE' ) ) {
return false;
}
return true;
}
);
return array_slice( $posts, 0, 3 ); // Max 3 posts.
}
/**
* Add UTM tags to links. Only add if UTM params are not already present.
*
* @param string $link Link.
* @param int $index Array index.
*/
private function add_utm_params( $link, $index ) {
// Skip if link has any UTM tags already set.
if ( preg_match( '/[?&]utm_[a-z_]+=/', $link ) ) {
return $link;
}
$utm_params = [
'utm_source' => 'Plugin',
'utm_medium' => 'Dashboard%20Widget%20Post%20' . ( $index + 1 ),
'utm_campaign' => 'WP',
];
return add_query_arg( $utm_params, $link );
}
/**
* Add footer in the admin dashboard widget.
*/
public function dashboard_widget_footer() {
?>
<div class="rank-math-widget-footer">
<a target="_blank" href="<?php KB::the( 'blog', 'Dashboard Widget Blog' ); ?>">
<?php esc_html_e( 'Blog', 'seo-by-rank-math' ); ?>
<span class="screen-reader-text"><?php esc_html_e( '(opens in a new window)', 'seo-by-rank-math' ); ?></span>
<span aria-hidden="true" class="dashicons dashicons-external"></span>
</a>
<a target="_blank" href="<?php KB::the( 'knowledgebase', 'Dashboard Widget Help' ); ?>">
<?php esc_html_e( 'Help', 'seo-by-rank-math' ); ?>
<span class="screen-reader-text"><?php esc_html_e( '(opens in a new window)', 'seo-by-rank-math' ); ?></span>
<span aria-hidden="true" class="dashicons dashicons-external"></span>
</a>
<?php if ( ! defined( 'RANK_MATH_PRO_FILE' ) ) { ?>
<a target="_blank" href="<?php KB::the( 'pro', 'Dashboard Widget PRO' ); ?>" class="rank-math-widget-go-pro">
<?php esc_html_e( 'Go Pro', 'seo-by-rank-math' ); ?>
<span class="screen-reader-text"><?php esc_html_e( '(opens in a new window)', 'seo-by-rank-math' ); ?></span>
<span aria-hidden="true" class="dashicons dashicons-external"></span>
</a>
<?php } ?>
</div>
<?php
}
/**
* Get posts.
*/
private function get_feed() {
$cache_key = 'rank_math_feed_posts_v2';
$cache = get_transient( $cache_key );
if ( false !== $cache ) {
return $cache;
}
$response = wp_remote_get( 'https://rankmath.com/wp-json/wp/v2/posts?dashboard_widget_feed=1' );
if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
set_transient( $cache_key, [], 2 * HOUR_IN_SECONDS );
return false;
}
$posts = json_decode( wp_remote_retrieve_body( $response ), true );
if ( empty( $posts ) || ! is_array( $posts ) ) {
set_transient( $cache_key, [], 2 * HOUR_IN_SECONDS );
return false;
}
set_transient( $cache_key, $posts, 12 * HOUR_IN_SECONDS );
return $posts;
}
}
@@ -0,0 +1,102 @@
<?php
/**
* The Import Export Class
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use WP_REST_Response;
use RankMath\Helper;
use RankMath\Runner;
use RankMath\Traits\Ajax;
use RankMath\Traits\Hooker;
use RankMath\Helpers\Param;
use RankMath\Status\Backup;
use RankMath\Admin\Importers\Detector;
defined( 'ABSPATH' ) || exit;
/**
* Import_Export class.
*/
class Import_Export implements Runner {
use Hooker;
use Ajax;
/**
* Register hooks.
*/
public function hooks() {
$this->ajax( 'clean_plugin', 'clean_plugin' );
$this->ajax( 'import_plugin', 'import_plugin' );
}
/**
* Get localized JSON data to be used on the Import & Export tab of the Status & Tools page.
*/
public static function get_json_data() {
$detector = new Detector();
$importable_plugins = $detector->detect();
return [
'backups' => Backup::get_backups(),
'importablePlugins' => $importable_plugins,
];
}
/**
* Handles AJAX run plugin clean.
*/
public function clean_plugin() {
$this->verify_nonce( 'rank-math-ajax-nonce' );
$this->has_cap_ajax( 'general' );
$result = Detector::run_by_slug( Param::post( 'pluginSlug' ), 'cleanup' );
if ( $result['status'] ) {
/* translators: Plugin name */
$this->success( sprintf( esc_html__( 'Cleanup of %s data successfully done.', 'seo-by-rank-math' ), $result['importer']->get_plugin_name() ) );
}
/* translators: Plugin name */
$this->error( sprintf( esc_html__( 'Cleanup of %s data failed.', 'seo-by-rank-math' ), $result['importer']->get_plugin_name() ) );
}
/**
* Handles AJAX run plugin import.
*/
public function import_plugin() {
$this->verify_nonce( 'rank-math-ajax-nonce' );
$this->has_cap_ajax( 'general' );
$perform = Param::post( 'perform', '', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK );
if ( ! $this->is_action_allowed( $perform ) ) {
$this->error( esc_html__( 'Action not allowed.', 'seo-by-rank-math' ) );
}
try {
$result = Detector::run_by_slug( Param::post( 'pluginSlug' ), 'import', $perform );
$this->success( $result );
} catch ( \Exception $e ) {
$this->error( $e->getMessage() );
}
}
/**
* Check if given action is in the list of allowed actions.
*
* @param string $perform Action to check.
*
* @return bool
*/
private function is_action_allowed( $perform ) {
$allowed = [ 'settings', 'postmeta', 'termmeta', 'usermeta', 'redirections', 'blocks', 'deactivate', 'locations', 'news', 'video', 'recalculate' ];
return $perform && in_array( $perform, $allowed, true );
}
}
@@ -0,0 +1,69 @@
<?php
/**
* The List Table Base CLass.
*
* @since 1.0.0
* @package RankMath
* @subpackage RankMath\Admin
* @author RankMath <support@rankmath.com>
*/
namespace RankMath\Admin;
use WP_List_Table;
use RankMath\Helpers\Param;
/**
* List_Table class.
*/
class List_Table extends WP_List_Table {
/**
* Message to be displayed when there are no items.
*/
public function no_items() {
echo isset( $this->_args['no_items'] ) ? wp_kses_post( $this->_args['no_items'] ) : esc_html__( 'No items found.', 'seo-by-rank-math' );
}
/**
* Get order setting.
*
* @return string
*/
protected function get_order() {
$order = Param::request( 'order', 'desc' );
return in_array( $order, [ 'desc', 'asc' ], true ) ? strtoupper( $order ) : 'DESC';
}
/**
* Get orderby setting.
*
* @param string $default_value (Optional) Extract order by from request.
*
* @return string
*/
protected function get_orderby( $default_value = 'create_date' ) {
return Param::get( 'orderby', $default_value, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK );
}
/**
* Get search query variable.
*
* @return bool|string
*/
protected function get_search() {
return Param::request( 's', false, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK );
}
/**
* Set column headers.
*
* @codeCoverageIgnore
*/
protected function set_column_headers() {
$this->_column_headers = [
$this->get_columns(),
[],
$this->get_sortable_columns(),
];
}
}
@@ -0,0 +1,113 @@
<?php
/**
* The admin-specific functionality of the plugin.
*
* @since 1.0.223
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Helper;
use RankMath\Helpers\Editor;
use RankMath\Helpers\Param;
use RankMath\Traits\Hooker;
defined( 'ABSPATH' ) || exit;
/**
* Lock_Modified_Date class.
*
* @codeCoverageIgnore
*/
class Lock_Modified_Date {
use Hooker;
/**
* Register hooks.
*/
public function __construct() {
$this->action( 'rest_api_init', 'init_rest_api' );
$this->action( 'wp_insert_post_data', 'update_modified_date', 999, 3 );
}
/**
* Add REST filter to modify the post object.
*/
public function init_rest_api() {
$post_types = Helper::get_allowed_post_types();
foreach ( $post_types as $post_type ) {
$this->filter( "rest_pre_insert_{$post_type}", 'update_last_modified_parameter', 99, 2 );
}
}
/**
* Add last_modified parameter to a post when a post is updated from Block Editor.
*
* @param WP_POST $prepared_post Post object.
* @param WP_REST_Request $request Request object.
*/
public function update_last_modified_parameter( $prepared_post, $request ) {
$params = $request->get_params();
if ( isset( $params['meta']['rank_math_lock_modified_date'] ) ) {
$prepared_post->lock_modified_date = ! empty( $params['meta']['rank_math_lock_modified_date'] );
}
return $prepared_post;
}
/**
* Lock Modified date by overwriting the old value.
*
* @param array $data An array of slashed, sanitized, and processed post data.
* @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data.
*/
public function update_modified_date( $data, $postarr ) {
$post_id = ! empty( $postarr['ID'] ) ? $postarr['ID'] : 0;
if (
! $post_id ||
! isset( $postarr['post_modified'], $postarr['post_modified_gmt'] ) ||
! $this->lock_modified_date( $postarr, $post_id )
) {
return $data;
}
$data['post_modified'] = $postarr['post_modified'];
$data['post_modified_gmt'] = $postarr['post_modified_gmt'];
return $data;
}
/**
* Whether to lock modified date.
*
* @param array $data An array of sanitized (and slashed) but otherwise unmodified post data.
* @param int $post_id Post ID.
*/
private function lock_modified_date( $data, $post_id ) {
if ( ! Editor::can_add_lock_modified_date() ) {
return false;
}
if ( Param::request( 'action' ) === 'et_fb_ajax_save' ) {
if (
empty( $_REQUEST['et_fb_save_nonce'] ) ||
! wp_verify_nonce( Param::request( 'et_fb_save_nonce' ), 'et_fb_save_nonce' )
) {
return false;
}
$options = ! empty( $_REQUEST['options'] ) ? $_REQUEST['options'] : []; //phpcs:ignore
return ! empty( $options['conditional_tags'] ) && ! empty( $options['conditional_tags']['lock_modified_date'] );
}
if ( Param::request( 'action' ) === 'elementor_ajax' ) {
return wp_verify_nonce( Param::request( '_nonce' ), 'elementor_ajax' ) && ! empty( $_REQUEST['lock_modified_date'] );
}
return isset( $data['lock_modified_date'] ) ? $data['lock_modified_date'] : Helper::get_post_meta( 'lock_modified_date', $post_id );
}
}
@@ -0,0 +1,322 @@
<?php
/**
* The admin notices.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Runner;
use RankMath\Helper;
use RankMath\Traits\Ajax;
use RankMath\Traits\Hooker;
use RankMath\Helpers\Sitepress;
use RankMath\Helpers\Param;
defined( 'ABSPATH' ) || exit;
/**
* Notices class.
*/
class Notices implements Runner {
use Hooker;
use Ajax;
/**
* Register hooks.
*/
public function hooks() {
$this->action( 'admin_init', 'notices' );
$this->action( 'wp_helpers_notification_dismissed', 'notice_dismissible' );
}
/**
* Run all notices routine.
*/
public function notices() {
$this->is_plugin_configured();
$this->new_post_type();
if ( Sitepress::get()->is_active() ) {
$this->convert_wpml_settings();
$this->display_wpml_notice();
}
$this->permalink_changes_warning();
$this->react_settings_ui_notice();
}
/**
* Show a persistent admin notice when the React Settings UI is disabled.
*
* Adds a dismissible, persistent error when the temporary option to
* disable the React-based Settings UI is turned off. The notice is removed
* when the React Settings UI is enabled again.
*
* @since 1.0.255
* @return void
*/
private function react_settings_ui_notice() {
// Only relevant for admins in the dashboard context.
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$notice_id = 'rank_math_react_settings_ui_disabled';
if ( ! Helper::is_react_enabled() ) {
$message = sprintf(
// Translators: 1: opening anchor tag, 2: closing anchor tag.
__( 'The React Settings UI is currently disabled, and the classic settings interface is active. Note: The PHP-based settings interface will be removed in an upcoming release. %1$sEnable the React Settings UI%2$s to switch back.', 'seo-by-rank-math' ),
'<a href="' . esc_url( Helper::get_dashboard_url() ) . '">',
'</a>'
);
Helper::add_notification(
$message,
[
'type' => 'error',
'id' => $notice_id,
]
);
return;
}
// React UI is enabled; ensure any prior notice is removed.
Helper::remove_notification( $notice_id );
}
/**
* Set known post type after notice dismissal.
*
* @param string $notification_id Notification id.
*/
public function notice_dismissible( $notification_id ) {
if ( 'new_post_type' === $notification_id ) {
$current = get_post_types( [ 'public' => true ] );
update_option( 'rank_math_known_post_types', $current );
if ( Helper::is_module_active( 'sitemap' ) ) {
\RankMath\Sitemap\Cache::invalidate_storage();
}
return;
}
if ( 'display_wpml_notice' === $notification_id ) {
update_option( 'rank_math_wpml_notice_dismissed', true );
}
if ( 'rank-math-site-url-mismatch' === $notification_id ) {
update_option( 'rank_math_siteurl_mismatch_notice_dismissed', true );
}
}
/**
* If plugin configuration not done.
*/
private function is_plugin_configured() {
if ( 'mts-install-plugins' === Param::get( 'page' ) ) {
return;
}
if ( rank_math()->notification->get_notification_by_id( 'plugin_not_setup' ) && ! Helper::is_configured() ) {
$message = sprintf(
'<b>Warning!</b> You didn\'t set up your Rank Math SEO plugin yet, which means you\'re missing out on essential settings and tweaks! <a href="%s">Complete your setup by clicking here.</a>',
Helper::get_admin_url( 'wizard' )
);
Helper::add_notification(
$message,
[
'type' => 'warning',
'id' => 'plugin_not_setup',
]
);
}
}
/**
* Add notification if a new post type is detected.
*/
private function new_post_type() {
$known = get_option( 'rank_math_known_post_types', [] );
$current = Helper::get_accessible_post_types();
$new = array_diff( $current, $known );
if ( empty( $new ) ) {
return;
}
$list = '<code>' . implode( '</code>, <code>', $new ) . '</code>';
/* Translators: placeholder is the post type name. */
$message = __( 'Rank Math has detected a new post type: %1$s. You may want to check the settings of the <a href="%2$s">Titles &amp; Meta page</a>.', 'seo-by-rank-math' );
$count = count( $new );
if ( $count > 1 ) {
/* Translators: placeholder is the post type names separated with commas. */
$message = __( 'Rank Math has detected new post types: %1$s. You may want to check the settings of the <a href="%2$s">Titles &amp; Meta page</a>.', 'seo-by-rank-math' );
}
$message = $this->do_filter( 'admin/notice/new_post_type', $message, $count );
$message = sprintf( wp_kses_post( $message ), $list, Helper::get_settings_url( 'titles', 'post-type-' . key( $new ) ), Helper::get_settings_url( 'sitemap', 'post-type-' . key( $new ) ) );
Helper::add_notification(
$message,
[
'type' => 'info',
'id' => 'new_post_type',
]
);
}
/**
* Function to show Show String Translation plugin notice and convert the settings.
*/
private function convert_wpml_settings() {
if ( ! function_exists( 'icl_get_languages' ) || get_option( 'rank_math_wpml_data_converted' ) ) {
return;
}
$languages = icl_get_languages(); // @phpstan-ignore-line
foreach ( $languages as $lang_code => $language ) {
foreach ( [ 'general', 'titles' ] as $option ) {
$data = get_option( "rank-math-options-{$option}_$lang_code" );
if ( empty( $data ) ) {
continue;
}
$common_data = array_intersect( array_keys( $data ), $this->get_translatable_options() );
if ( empty( $common_data ) ) {
continue;
}
foreach ( $common_data as $option_key ) {
$string_id = icl_get_string_id( Helper::get_settings( "$option.$option_key" ), "admin_texts_rank-math-options-$option" ); // @phpstan-ignore-line
icl_add_string_translation( $string_id, $lang_code, $data[ $option_key ], 10 ); // @phpstan-ignore-line
}
}
}
update_option( 'rank_math_wpml_data_converted', true );
}
/**
* Display WPML notice.
*
* @return void
*/
private function display_wpml_notice() {
if ( function_exists( 'icl_add_string_translation' ) || get_option( 'rank_math_wpml_notice_dismissed' ) ) {
return;
}
$sitepress = Sitepress::get()->get_var();
$setup_complete = $sitepress->get_setting( 'setup_complete', false );
if ( ! $setup_complete ) {
return;
}
Helper::add_notification(
__( 'Please activate the WPML String Translation plugin to convert Rank Math Setting values in different languages.', 'seo-by-rank-math' ),
[
'type' => 'error',
'id' => 'display_wpml_notice',
]
);
}
/**
* Get Translatable option keys.
*
* @return array
*/
private function get_translatable_options() {
$options = [
'img_alt_format',
'img_title_format',
'breadcrumbs_separator',
'breadcrumbs_prefix',
'breadcrumbs_home_link',
'breadcrumbs_home_label',
'breadcrumbs_archive_format',
'breadcrumbs_search_format',
'breadcrumbs_404_label',
'rss_before_content',
'rss_after_content',
'title_separator',
'homepage_title',
'homepage_description',
'homepage_facebook_title',
'homepage_facebook_description',
'author_archive_title',
'author_archive_description',
'date_archive_title',
'date_archive_description',
'search_title',
'404_title',
];
$post_types = Helper::get_accessible_post_types();
foreach ( $post_types as $post_type => $data ) {
$options = array_merge(
$options,
[
"pt_{$post_type}_title",
"pt_{$post_type}_description",
"pt_{$post_type}_archive_title",
"pt_{$post_type}_archive_description",
"pt_{$post_type}_default_snippet_name",
"pt_{$post_type}_default_snippet_desc",
]
);
}
$taxonomies = Helper::get_accessible_taxonomies();
foreach ( $taxonomies as $taxonomy => $data ) {
$options = array_merge(
$options,
[
"tax_{$taxonomy}_title",
"tax_{$taxonomy}_description",
]
);
}
return $options;
}
/**
* Maybe add notice on Permalinks page about the risks of changing the permalinks on a live site.
*
* @return void
*/
public function permalink_changes_warning() {
global $pagenow;
if ( 'options-permalink.php' !== $pagenow ) {
return;
}
$this->action( 'admin_enqueue_scripts', 'add_permalink_changes_warning', 12 );
}
/**
* Add the notice for the Permalinks page.
*
* @return void
*/
public function add_permalink_changes_warning() {
wp_enqueue_script( 'rank-math-core-permalink-settings' );
$message = __( '<b>Rank Math Warning:</b> Changing the permalinks on a live, indexed site may result in serious loss of traffic if done incorrectly. Consider adding a new redirection from the old URL format to the new one.', 'seo-by-rank-math' );
Helper::add_notification(
$message,
[
'type' => 'warning',
'screen' => 'options-permalink',
'classes' => 'hidden rank-math-notice-permalinks-warning is-dismissible',
]
);
}
}
@@ -0,0 +1,658 @@
<?php
/**
* The option center of the plugin.
*
* @since 1.0.9
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\KB;
use RankMath\CMB2;
use RankMath\Helper;
use RankMath\Runner;
use RankMath\Traits\Hooker;
use RankMath\Helpers\Arr;
use RankMath\Helpers\Param;
use RankMath\Wizard\Search_Console;
use RankMath\Admin\Sanitize_Settings;
defined( 'ABSPATH' ) || exit;
/**
* Option_Center class.
*/
class Option_Center implements Runner {
use Hooker;
/**
* Register hooks.
*/
public function hooks() {
$this->action( 'init', 'register_general_settings', 125 );
$this->action( 'init', 'register_title_settings', 125 );
$this->filter( 'rank_math/settings/title', 'title_post_type_settings', 1 );
$this->filter( 'rank_math/settings/title', 'title_taxonomy_settings', 1 );
$this->filter( 'rank_math/settings/general', 'remove_unwanted_general_tabs', 1 );
$this->action( 'admin_enqueue_scripts', 'enqueue_settings_translations', 11 );
}
/**
* General Settings.
*/
public function register_general_settings() {
$tabs = [
'links' => [
'icon' => 'rm-icon rm-icon-link',
'title' => esc_html__( 'Links', 'seo-by-rank-math' ),
/* translators: Link to kb article */
'desc' => sprintf( esc_html__( 'Change how some of the links open and operate on your website. %s.', 'seo-by-rank-math' ), '<a href="' . KB::get( 'link-settings', 'Options Panel Links Tab' ) . '" target="_blank">' . esc_html__( 'Learn More', 'seo-by-rank-math' ) . '</a>' ),
],
'breadcrumbs' => [
'icon' => 'rm-icon rm-icon-direction',
'title' => esc_html__( 'Breadcrumbs', 'seo-by-rank-math' ),
'classes' => 'rank-math-advanced-option',
/* translators: Link to kb article */
'desc' => sprintf( esc_html__( 'Here you can set up the breadcrumbs function. %s', 'seo-by-rank-math' ), '<a href="' . KB::get( 'breadcrumbs', 'Options Panel Breadcrumbs Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>. <br/>' ),
'after_row' => current_theme_supports( 'rank-math-breadcrumbs' ) ? '' : '<div class="notice notice-alt notice-warning warning inline rank-math-notice"><p>' . esc_html__( 'Use the following code in your theme template files to display breadcrumbs.', 'seo-by-rank-math' ) . ' <a href="' . KB::get( 'breadcrumbs-install', 'Options Panel Breadcrumbs Tab' ) . '" target="_blank">' . esc_html__( 'Learn More', 'seo-by-rank-math' ) . '</a><br /><code>&lt;?php if (function_exists(\'rank_math_the_breadcrumbs\')) rank_math_the_breadcrumbs(); ?&gt;</code> OR <code>[rank_math_breadcrumb]</code></p></div>',
],
'webmaster' => [
'icon' => 'rm-icon rm-icon-toolbox',
'title' => esc_html__( 'Webmaster Tools', 'seo-by-rank-math' ),
/* translators: Link to kb article */
'desc' => sprintf( esc_html__( 'Enter verification codes for third-party webmaster tools. %s', 'seo-by-rank-math' ), '<a href="' . KB::get( 'webmaster-tools', 'Options Panel Webmaster Tools Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>.<br />' ),
],
'others' => [
'icon' => 'rm-icon rm-icon-misc',
'title' => esc_html__( 'Others', 'seo-by-rank-math' ),
/* translators: Link to kb article */
'desc' => sprintf( esc_html__( 'Change some uncommon but essential settings here. %s.', 'seo-by-rank-math' ), '<a href="' . KB::get( 'other-settings', 'Options Panel Others Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>' ),
'classes' => 'rank-math-advanced-option',
],
];
if ( is_super_admin() && 'rank-math-options-general' === Param::get( 'page' ) ) {
Arr::insert(
$tabs,
[
'htaccess' => [
'icon' => 'rm-icon rm-icon-htaccess',
'title' => esc_html__( 'Edit .htaccess', 'seo-by-rank-math' ),
/* translators: Link to kb article */
'desc' => sprintf( esc_html__( 'Edit the contents of your .htaccess file easily. %s.', 'seo-by-rank-math' ), '<a href="' . KB::get( 'edit-htaccess', 'Options Panel htaccess Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>' ),
'classes' => 'rank-math-advanced-option',
'json' => [
'htaccessData' => Admin_Helper::get_htaccess_data(),
],
],
],
5
);
}
/**
* Allow developers to add new sections in the General Settings.
*
* @param array $tabs
*/
$tabs = $this->do_filter( 'settings/general', $tabs );
new Register_Options_Page(
[
'key' => 'rank-math-options-general',
'title' => esc_html__( 'SEO Settings', 'seo-by-rank-math' ),
'menu_title' => esc_html__( 'General Settings', 'seo-by-rank-math' ),
'capability' => 'rank_math_general',
'folder' => 'general',
'tabs' => $tabs,
]
);
}
/**
* Remove unneeded tabs from the General Settings.
*
* @param array $tabs Hold tabs for optional panel.
* @return array
*/
public function remove_unwanted_general_tabs( $tabs ) {
if ( is_multisite() ) {
unset( $tabs['robots'] );
}
if ( ! Helper::has_cap( 'edit_htaccess' ) && is_multisite() ) {
unset( $tabs['htaccess'] );
}
return $tabs;
}
/**
* Register SEO Titles & Meta Settings.
*/
public function register_title_settings() {
$homepage_notice = '';
if ( 'page' === get_option( 'show_on_front' ) ) {
$home_page_id = get_option( 'page_on_front' );
if ( ! $home_page_id ) {
$home_page_id = get_option( 'page_for_posts' );
}
$homepage_notice = '<a href="' . admin_url( 'post.php?post=' . $home_page_id . '&action=edit' ) . '">' . esc_html__( 'Edit Page: ', 'seo-by-rank-math' ) . get_the_title( $home_page_id ) . '</a>';
}
$tabs = [
'global' => [
'icon' => 'rm-icon rm-icon-settings',
'title' => esc_html__( 'Global Meta', 'seo-by-rank-math' ),
/* translators: Link to KB article */
'desc' => sprintf( esc_html__( 'Change Global meta settings that take effect across your website. %s.', 'seo-by-rank-math' ), '<a href="' . KB::get( 'titles-meta', 'Options Panel Meta Global Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>' ),
'json' => [
'overlayImages' => array_merge( [ '' => __( 'Off', 'seo-by-rank-math' ) ], Helper::choices_overlay_images( 'names' ) ),
],
],
'local' => [
'icon' => 'rm-icon rm-icon-local-seo',
'title' => esc_html__( 'Local SEO', 'seo-by-rank-math' ),
/* translators: Redirection page url */
'desc' => sprintf( wp_kses_post( __( 'Optimize for local searches and Knowledge Graph using these settings. %s.', 'seo-by-rank-math' ) ), '<a href="' . KB::get( 'local-seo-settings', 'Options Panel Meta Local Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>' ),
'after_row' => '<div class="notice notice-alt notice-info info inline rank-math-notice"><p>' . __( 'Use the <code>[rank_math_contact_info]</code> shortcode to display contact information in a nicely formatted way. You should also claim your business on Google if you have not already.', 'seo-by-rank-math' ) . '</p></div>',
],
'social' => [
'icon' => 'rm-icon rm-icon-social',
'title' => esc_html__( 'Social Meta', 'seo-by-rank-math' ),
/* translators: Link to social setting KB article */
'desc' => sprintf( esc_html__( "Add social account information to your website's Schema and Open Graph. %s.", 'seo-by-rank-math' ), '<a href="' . KB::get( 'social-meta-settings', 'Options Panel Meta Social Tab' ) . '" target="_blank">' . esc_html__( 'Learn More', 'seo-by-rank-math' ) . '</a>' ),
],
'homepage' => [
'icon' => 'rm-icon rm-icon-home',
'title' => esc_html__( 'Homepage', 'seo-by-rank-math' ),
'desc' => sprintf(
/* translators: Link to KB article */
esc_html__( 'Add SEO meta and OpenGraph details to your homepage. %s.', 'seo-by-rank-math' ),
'<a href="' . KB::get( 'homepage-settings', 'Options Panel Meta Home Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>'
),
'json' => [
'staticHomePageNotice' => $homepage_notice,
],
],
'author' => [
'icon' => 'rm-icon rm-icon-users',
'title' => esc_html__( 'Authors', 'seo-by-rank-math' ),
/* translators: Link to KB article */
'desc' => sprintf( esc_html__( 'Change SEO options related to the author archives. %s.', 'seo-by-rank-math' ), '<a href="' . KB::get( 'author-settings', 'Options Panel Meta Author Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>' ),
'json' => [
'disableAutorArchive' => $this->do_filter( 'settings/titles/disable_author_archives', 'off' ),
],
],
'misc' => [
'icon' => 'rm-icon rm-icon-misc',
'title' => esc_html__( 'Misc Pages', 'seo-by-rank-math' ),
/* translators: Link to KB article */
'desc' => sprintf( esc_html__( 'Customize SEO meta settings of pages like search results, 404s, etc. %s.', 'seo-by-rank-math' ), '<a href="' . KB::get( 'misc-settings', 'Options Panel Meta Misc Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>' ),
],
];
/**
* Allow developers to add new section in the Title Settings.
*
* @param array $tabs
*/
$tabs = $this->do_filter( 'settings/title', $tabs );
new Register_Options_Page(
[
'key' => 'rank-math-options-titles',
'title' => esc_html__( 'SEO Titles &amp; Meta', 'seo-by-rank-math' ),
'menu_title' => esc_html__( 'Titles &amp; Meta', 'seo-by-rank-math' ),
'capability' => 'rank_math_titles',
'folder' => 'titles',
'tabs' => $tabs,
]
);
if ( is_admin() ) {
Helper::add_json( 'postTitle', 'Post Title' );
Helper::add_json( 'postUri', home_url( '/post-title' ) );
Helper::add_json( 'blogName', get_bloginfo( 'name' ) );
}
}
/**
* Add post type tabs in the Title Settings panel.
*
* @param array $tabs Holds the tabs of the options panel.
* @return array
*/
public function title_post_type_settings( $tabs ) {
$icons = Helper::choices_post_type_icons();
$links = [
'post' => '<a href="' . KB::get( 'post-settings', 'Options Panel Meta Posts Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>.',
'page' => '<a href="' . KB::get( 'page-settings', 'Options Panel Meta Pages Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>.',
'product' => '<a href="' . KB::get( 'product-settings', 'Options Panel Meta Products Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>.',
'attachment' => '<a href="' . KB::get( 'media-settings', 'Options Panel Meta Attachments Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>.',
];
$names = [
'post' => 'single %s',
'page' => 'single %s',
'product' => 'product pages',
'attachment' => 'media %s',
];
$tabs['p_types'] = [
'title' => esc_html__( 'Post Types:', 'seo-by-rank-math' ),
'type' => 'separator',
'name' => 'p_types_separator',
];
foreach ( Helper::get_accessible_post_types() as $post_type ) {
$obj = get_post_type_object( $post_type );
$link = isset( $links[ $obj->name ] ) ? $links[ $obj->name ] : '';
$obj_name = isset( $names[ $obj->name ] ) ? sprintf( $names[ $obj->name ], $obj->name ) : $obj->name;
$is_attachment = $post_type === 'attachment';
$richsnp_default = 'off';
if ( ( class_exists( 'WooCommerce' ) && 'product' === $post_type ) || ( class_exists( 'Easy_Digital_Downloads' ) && 'download' === $post_type ) ) {
$richsnp_default = 'product';
}
if ( $post_type === 'post' ) {
$richsnp_default = 'article';
}
$primary_taxonomy_hash = [
'post' => 'category',
'product' => 'product_cat',
];
$tabs[ 'post-type-' . $obj->name ] = [
'title' => $is_attachment ? esc_html__( 'Attachments', 'seo-by-rank-math' ) : $obj->label,
'icon' => isset( $icons[ $obj->name ] ) ? $icons[ $obj->name ] : $icons['default'],
/* translators: 1. post type name 2. link */
'desc' => sprintf( esc_html__( 'Change Global SEO, Schema, and other settings for %1$s. %2$s', 'seo-by-rank-math' ), $obj_name, $link ),
'post_type' => $obj->name,
'file' => rank_math()->includes_dir() . 'settings/titles/post-types.php',
'classes' => 'attachment' === $post_type ? 'rank-math-advanced-option' : '',
'json' => [
'isWooCommerceActive' => class_exists( 'WooCommerce' ),
'isEddActive' => class_exists( 'Easy_Digital_Downloads' ),
'isWebStoriesActive' => defined( 'WEBSTORIES_VERSION' ),
$post_type => [
'title' => $is_attachment ? esc_html__( 'Attachments', 'seo-by-rank-math' ) : $obj->label,
'name' => $is_attachment ? esc_html__( 'Media', 'seo-by-rank-math' ) : $obj->labels->singular_name,
'schemaTypes' => Helper::choices_rich_snippet_types( esc_html__( 'None (Click here to set one)', 'seo-by-rank-math' ), $post_type ),
'taxonomies' => Helper::get_object_taxonomies( $post_type ),
'hasArchive' => $obj->has_archive,
'customRobots' => false,
'schemaDefault' => $this->do_filter( 'settings/snippet/type', $richsnp_default, $post_type ),
'articleType' => $this->do_filter( 'settings/snippet/article_type', 'post' === $post_type ? 'BlogPosting' : 'Article', $post_type ),
'enableLinkSuggestion' => $this->do_filter( 'settings/titles/link_suggestions', true, $post_type ),
'primaryTaxonomy' => isset( $primary_taxonomy_hash[ $post_type ] ) ? $primary_taxonomy_hash[ $post_type ] : 'off',
],
],
];
}
return $tabs;
}
/**
* Add taxonomy tabs in the Title Settings panel.
*
* @param array $tabs Holds the tabs of the options panel.
* @return array
*/
public function title_taxonomy_settings( $tabs ) {
$icons = Helper::choices_taxonomy_icons();
$hash_name = [
'category' => 'category archive pages',
'product_cat' => 'Product category pages',
'product_tag' => 'Product tag pages',
];
$hash_link = [
'category' => '<a href="' . KB::get( 'category-settings', 'Options Panel Meta Categories Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>.',
'post_tag' => '<a href="' . KB::get( 'tag-settings', 'Options Panel Meta Tags Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>.',
'product_cat' => '<a href="' . KB::get( 'product-categories-settings', 'Options Panel Meta Product Categories Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>.',
'product_tag' => '<a href="' . KB::get( 'product-tags-settings', 'Options Panel Meta Product Tags Tab' ) . '" target="_blank">' . esc_html__( 'Learn more', 'seo-by-rank-math' ) . '</a>.',
];
$taxonomies_data = [];
foreach ( Helper::get_accessible_taxonomies() as $taxonomy ) {
$attached = implode( ' + ', $taxonomy->object_type );
$taxonomies_data[ $attached ][ $taxonomy->name ] = $taxonomy;
}
foreach ( $taxonomies_data as $attached => $taxonomies ) {
// Separator.
$tabs[ $attached ] = [
'title' => ucwords( $attached ) . ':',
'type' => 'separator',
'name' => 'taxonomy_separator',
];
foreach ( $taxonomies as $taxonomy ) {
$link = isset( $hash_link[ $taxonomy->name ] ) ? $hash_link[ $taxonomy->name ] : '';
$taxonomy_name = isset( $hash_name[ $taxonomy->name ] ) ? $hash_name[ $taxonomy->name ] : $taxonomy->label;
$tabs[ 'taxonomy-' . $taxonomy->name ] = [
'icon' => isset( $icons[ $taxonomy->name ] ) ? $icons[ $taxonomy->name ] : $icons['default'],
'title' => $taxonomy->label,
/* translators: 1. taxonomy name 2. link */
'desc' => sprintf( esc_html__( 'Change Global SEO, Schema, and other settings for %1$s. %2$s', 'seo-by-rank-math' ), $taxonomy_name, $link ),
'taxonomy' => $taxonomy->name,
'file' => rank_math()->includes_dir() . 'settings/titles/taxonomies.php',
];
}
}
if ( isset( $tabs['taxonomy-post_format'] ) ) {
$tab = $tabs['taxonomy-post_format'];
unset( $tabs['taxonomy-post_format'] );
$tab['title'] = esc_html__( 'Post Formats', 'seo-by-rank-math' );
$tab['page_title'] = esc_html__( 'Post Formats Archive', 'seo-by-rank-math' );
Arr::insert( $tabs, [ 'taxonomy-post_format' => $tab ], 5 );
}
return $tabs;
}
/**
* Save Settings data. Called from the `updateSettings` endpoint.
*
* @param string $type Settings type.
* @param array $settings Settings data.
* @param array $field_types Field ids with types use to sanitize the value.
* @param array $updated Array of field ids that were updated.
* @param bool $is_reset Whether the request is to reset the data.
* @return array
*/
public static function save_settings( $type, $settings, $field_types, $updated, $is_reset ) {
$notifications = [];
$update_htaccess = self::maybe_update_htaccess( $settings );
if ( ! empty( $update_htaccess ) ) {
$notifications[] = $update_htaccess;
}
$update_analytics = self::maybe_update_analytics( $settings, $updated );
if ( ! empty( $update_analytics ) ) {
$notifications[] = $update_analytics;
}
do_action( 'rank_math/settings/before_save', $type, $settings );
foreach (
[
'htaccess_allow_editing',
'htaccess_content',
'searchConsole',
'analyticsData',
'analytics',
'usage_tracking',
] as $key
) {
if ( isset( $settings[ $key ] ) ) {
unset( $settings[ $key ] );
}
}
$settings = Sanitize_Settings::sanitize( $settings, $field_types );
self::check_updated_fields( $updated, $is_reset );
// Get current settings to compare with new settings.
$current_settings = Helper::get_settings( $type );
// Only update fields that have actually changed.
$changed_settings = self::get_changed_settings( $current_settings, $settings );
// If no settings have changed, return early.
if ( empty( $changed_settings ) ) {
return [
'notifications' => $notifications,
'settings' => $current_settings,
];
}
$map = [
'general' => [ $changed_settings, null, null ],
'titles' => [ null, $changed_settings, null ],
'sitemap' => [ null, null, $changed_settings ],
];
Helper::update_all_settings( ...$map[ $type ] );
rank_math()->settings->reset();
do_action( 'rank_math/settings/after_save', $type, $changed_settings );
return [
'notifications' => $notifications,
'settings' => apply_filters( 'rank_math/settings/saved_data', Helper::get_settings( $type ), $type ),
];
}
/**
* Update Analytics data.
*
* @param array $settings Settings data.
* @param string $updated View that was updated.
*/
public static function maybe_update_analytics( $settings, $updated ) {
if ( empty( $updated ) || ( ! in_array( 'searchConsole', $updated, true ) && ! in_array( 'analyticsData', $updated, true ) ) ) {
return;
}
Search_Console::save( $settings );
$days = $settings['console_caching_control'] ?? 90;
$search_console = $settings['searchConsole'] ?? [];
if ( in_array( 'searchConsole', $updated, true ) && ! empty( $search_console ) ) {
$search_console['days'] = $days;
$response = \RankMath\Analytics\AJAX::get()->do_save_analytic_profile( $search_console );
if ( is_wp_error( $response ) ) {
return [
'error' => $response->get_error_message(),
];
}
}
$google_analytics = $settings['analyticsData'] ?? [];
if ( in_array( 'analyticsData', $updated, true ) && ! empty( $google_analytics ) ) {
$google_analytics['days'] = $days;
$response = \RankMath\Analytics\AJAX::get()->do_save_analytic_options( $google_analytics );
if ( is_wp_error( $response ) ) {
return [
'error' => $response->get_error_message(),
];
}
}
}
/**
* Enqueue settings translations when React UI is enabled as the settings pages are loaded in chunks.
*/
public function enqueue_settings_translations() {
if ( ! Helper::is_react_enabled() ) {
return;
}
$page = str_replace( 'rank-math-options-', '', Param::get( 'page', '' ) );
$hash = [
'general' => 'generalSettings',
'titles' => 'titleSettings',
'sitemap' => 'sitemapSettings',
'instant-indexing' => 'instantIndexingSettings',
];
if ( ! isset( $hash[ $page ] ) ) {
return;
}
$chunk = $hash[ $page ];
wp_enqueue_script( 'rank-math-settings-chunk', rank_math()->plugin_url() . "assets/admin/js/$chunk.js", [ 'rank-math-options' ], rank_math()->version, true );
wp_set_script_translations( 'rank-math-settings-chunk', 'seo-by-rank-math', rank_math()->plugin_dir() . 'languages/' );
wp_set_script_translations( 'rank-math-options', 'seo-by-rank-math', rank_math()->plugin_dir() . 'languages/' );
wp_set_script_translations( 'rank-math-components', 'seo-by-rank-math', rank_math()->plugin_dir() . 'languages/' );
$this->do_action( 'admin/after_settings_scripts' );
}
/**
* Check if certain fields got updated.
*
* @param array $updated Updated fields id.
* @param bool $is_reset Whether to reset the settings.
*/
private static function check_updated_fields( $updated, $is_reset ) {
if ( $is_reset ) {
Helper::schedule_flush_rewrite();
return;
}
/**
* Filter: Allow developers to add option fields which will flush the rewrite rules when updated.
*
* @param array $flush_fields Array of field IDs for which we need to flush.
*/
$flush_fields = apply_filters(
'rank_math/flush_fields',
[
'strip_category_base',
'disable_author_archives',
'url_author_base',
'attachment_redirect_urls',
'attachment_redirect_default',
'nofollow_external_links',
'nofollow_image_links',
'nofollow_domains',
'nofollow_exclude_domains',
'new_window_external_links',
'redirections_header_code',
'redirections_post_redirect',
'redirections_debug',
]
);
foreach ( $flush_fields as $field_id ) {
if ( in_array( $field_id, $updated, true ) ) {
Helper::schedule_flush_rewrite();
break;
}
}
}
/**
* Get only the settings that have changed.
*
* @param array $current_settings Current settings from database.
* @param array $new_settings New settings to be saved.
* @return array
*/
private static function get_changed_settings( $current_settings, $new_settings ) {
// Filter out invalid keys from both arrays.
$new_settings = array_filter( $new_settings, [ __CLASS__, 'is_valid_key' ], ARRAY_FILTER_USE_KEY );
$current_settings = array_filter( $current_settings, [ __CLASS__, 'is_valid_key' ], ARRAY_FILTER_USE_KEY );
// Merge current settings with new settings, new settings take precedence.
return array_merge( $current_settings, $new_settings );
}
/**
* Check if a key is valid for settings.
*
* @param mixed $key The key to validate.
* @return bool
*/
private static function is_valid_key( $key ) {
return is_string( $key ) && ! empty( $key );
}
/**
* Update .htaccess.
*
* @param array { $settings } Settings data.
*/
private static function maybe_update_htaccess( $settings ) {
if ( empty( $settings['htaccess_allow_editing'] ) ) {
return;
}
if ( ! is_super_admin() || ! Helper::has_cap( 'general' ) || ! Helper::has_cap( 'edit_htaccess' ) ) {
return [
'error' => esc_html__( 'You do not have permission to edit the .htaccess file.', 'seo-by-rank-math' ),
];
}
if ( ! Helper::is_edit_allowed() ) {
return [
'error' => esc_html__( 'You do not have permission to edit the .htaccess file.', 'seo-by-rank-math' ),
];
}
// phpcs:ignore= WordPress.Security.ValidatedSanitizedInput -- Writing to .htaccess file and escaping for HTML will break functionality.
$content = isset( $settings['htaccess_content'] ) ? $settings['htaccess_content'] : '';
if ( empty( $content ) ) {
return;
}
if ( ! self::do_htaccess_backup() ) {
return [
'error' => esc_html__( 'Failed to backup .htaccess file. Please check file permissions.', 'seo-by-rank-math' ),
];
}
if ( ! self::do_htaccess_update( $content ) ) {
return [
'error' => esc_html__( 'Failed to update .htaccess file. Please check file permissions.', 'seo-by-rank-math' ),
];
}
return [
'success' => esc_html__( '.htaccess file updated successfully.', 'seo-by-rank-math' ),
];
}
/**
* Create htaccess backup.
*
* @return bool
*/
private static function do_htaccess_backup() {
if ( ! Helper::is_filesystem_direct() ) {
return false;
}
$wp_filesystem = Helper::get_filesystem();
$path = get_home_path();
$file = $path . '.htaccess';
if ( ! $wp_filesystem->is_writable( $path ) || ! $wp_filesystem->exists( $file ) ) {
return false;
}
$backup = $path . uniqid( '.htaccess_back_' );
return $wp_filesystem->copy( $file, $backup, true );
}
/**
* Update htaccess file.
*
* @param string $content Htaccess content.
* @return string|bool
*/
private static function do_htaccess_update( $content ) {
if ( empty( $content ) || ! Helper::is_filesystem_direct() ) {
return false;
}
$wp_filesystem = Helper::get_filesystem();
$htaccess_file = get_home_path() . '.htaccess';
return ! $wp_filesystem->is_writable( $htaccess_file ) ? false : $wp_filesystem->put_contents( $htaccess_file, $content );
}
}
@@ -0,0 +1,305 @@
<?php
/**
* The option page functionality of the plugin.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use WP_Http;
use RankMath\KB;
use RankMath\CMB2;
use RankMath\Helper;
use RankMath\Traits\Hooker;
use RankMath\Helpers\Str;
use RankMath\Helpers\Param;
use RankMath\Robots_Txt;
use RankMath\Sitemap\Router;
use RankMath\Sitemap\Sitemap;
use RankMath\Admin\Page;
defined( 'ABSPATH' ) || exit;
/**
* Options class.
*/
class Options {
use Hooker;
/**
* Page title.
*
* @var string
*/
public $title = 'Settings';
/**
* Menu title.
*
* @var string
*/
public $menu_title = 'Settings';
/**
* Hold tabs for page.
*
* @var array
*/
public $tabs = [];
/**
* Hold folder name for tab files.
*
* @var string
*/
public $folder = '';
/**
* Menu Position.
*
* @var int
*/
public $position = 10;
/**
* The capability required for this menu to be displayed to the user.
*
* @var string
*/
public $capability = 'manage_options';
/**
* CMB2 option page id.
*
* @var string
*/
private $cmb_id = null;
/**
* Options key.
*
* @var string
*/
public $key = '';
/**
* The Constructor
*
* @param array $config Array of configuration.
*/
public function __construct( $config ) {
$this->config( $config );
$this->cmb_id = $this->key . '_options';
$this->action( 'admin_post_' . $this->key, 'reset_options', 2 );
}
/**
* Create option object and add settings.
*/
public function register_option_page() {
$current_page = str_replace( 'rank-math-options-', '', $this->key );
new Page(
$this->key,
$this->title,
[
'position' => $this->position,
'priority' => 9999,
'parent' => 'rank-math',
'capability' => $this->capability,
'menu_title' => $this->menu_title,
'render' => [ $this, 'display' ],
'classes' => $this->get_body_class(),
'assets' => [
'styles' => [
'select2-rm' => '',
'rank-math-common' => '',
'rank-math-cmb2' => '',
'wp-components' => '',
'rank-math-options' => rank_math()->plugin_url() . 'assets/admin/css/option-panel.css',
],
'scripts' => [
'media-editor' => '',
'underscore' => '',
'select2-rm' => '',
'lodash' => '',
'rank-math-common' => '',
'wp-api-fetch' => '',
'wp-data' => '',
'rank-math-components' => '',
'rank-math-options' => rank_math()->plugin_url() . 'assets/admin/js/settings.js',
],
'json' => $this->get_json_data( $current_page ),
],
]
);
}
/**
* Set the default values if not set.
*
* @param CMB2 $cmb The CMB2 object to hookup.
*/
public function set_defaults( $cmb ) {
foreach ( $cmb->prop( 'fields' ) as $id => $field_args ) {
$field = $cmb->get_field( $id );
if ( isset( $field_args['default'] ) || isset( $field_args['default_cb'] ) ) {
$defaults[ $id ] = $field->get_default();
}
}
// Save Defaults if any.
if ( ! empty( $defaults ) ) {
add_option( $this->key, $defaults );
}
}
/**
* Reset options.
*/
public function reset_options() {
if ( ! check_admin_referer( 'rank-math-reset-options' ) || ! current_user_can( 'manage_options' ) ) {
return false;
}
$url = wp_get_referer();
if ( ! $url ) {
$url = admin_url();
}
if ( filter_has_var( INPUT_POST, 'reset-cmb' ) && Param::post( 'action' ) === $this->key ) {
delete_option( $this->key );
Helper::redirect( esc_url_raw( $url ), WP_Http::SEE_OTHER );
exit;
}
}
/**
* Add classes to <body> of WordPress admin.
*
* @return string
*/
public function get_body_class() {
$mode = Helper::is_advanced_mode() ? 'advanced' : 'basic';
return [
'rank-math-page ',
'rank-math-mode-' . $mode,
];
}
/**
* Display Setting on a page.
*/
public function display() {
?>
<div id="rank-math-options" class="<?php echo esc_attr( $this->cmb_id ); ?>"></div>
<?php
}
/**
* Get setting tabs.
*
* @return array
*/
private function get_tabs() {
$filter = str_replace( '-', '_', str_replace( 'rank-math-', '', $this->key ) );
/**
* Allow developers to add new tabs into option panel.
*
* The dynamic part of hook is, page name without 'rank-math-' prefix.
*
* @param array $tabs
*/
return $this->do_filter( "admin/options/{$filter}_tabs", $this->tabs );
}
/**
* Get localized data for the current settings page.
*
* @param string $current_page Current Settings page.
*
* @return array
*/
private function get_json_data( $current_page ) {
if ( Param::get( 'page' ) !== $this->key ) {
return [];
}
if ( is_admin() ) {
rank_math()->variables->setup();
rank_math()->variables->setup_json();
}
$tabs = $this->get_tabs();
$data = $this->do_filter(
"admin/options/{$current_page}_data",
[
'isPro' => defined( 'RANK_MATH_PRO_FILE' ),
'tabs' => array_keys( $tabs ),
'optionPage' => $current_page,
'homeUrl' => get_home_url(),
'data' => $current_page === 'instant-indexing' ? get_option( 'rank-math-options-instant-indexing' ) : Helper::get_settings( $current_page ),
'isSiteConnected' => Helper::is_site_connected(),
'choices' => [
'postTypes' => Helper::choices_post_types(),
'accessiblePostTypes' => Helper::get_accessible_post_types(),
'accessibleTaxonomies' => Helper::get_accessible_taxonomies(),
'choicesPostTypeIcons' => Helper::choices_post_type_icons(),
'choicesTaxonomyIcons' => Helper::choices_taxonomy_icons(),
],
]
);
foreach ( $tabs as $tab ) {
if ( empty( $tab['json'] ) ) {
continue;
}
$data = array_merge( $data, $tab['json'] );
}
$method = "get_{$current_page}_data";
if ( ! method_exists( $this, $method ) ) {
return $data;
}
return array_merge( $data, $this->$method() );
}
/**
* Get General Settings page data.
*
* @return array
*/
private function get_general_data() {
return [
'activateUrl' => Admin_Helper::get_activate_url( admin_url( 'admin.php??page=rank-math-options-general&tab=content-ai' ) ),
'hasBreadcrumbSupport' => current_theme_supports( 'rank-math-breadcrumbs' ),
'showBlogPage' => 'page' === get_option( 'show_on_front' ) && get_option( 'page_for_posts' ) > 0,
'isEditAllowed' => Helper::is_edit_allowed(),
'defaultLanguage' => Helper::content_ai_default_language(),
];
}
/**
* Get General Settings page data.
*
* @return array
*/
private function get_titles_data() {
$data = [
'choicesRobots' => Helper::choices_robots(),
'supportsTitleTag' => current_theme_supports( 'title-tag' ) || wp_is_block_theme(),
'schemaTypes' => Helper::choices_rich_snippet_types( esc_html__( 'None (Click here to set one)', 'seo-by-rank-math' ) ),
'isRedirectAttachments' => Helper::get_settings( 'general.attachment_redirect_urls' ),
];
return $data;
}
}
@@ -0,0 +1,380 @@
<?php
/**
* The admin-page functionality.
*
* @since 1.0.0
* @package RankMath
* @subpackage RankMath\Admin
* @author RankMath <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Helpers\Param;
use RankMath\Helper;
/**
* Page class.
*/
class Page {
/**
* Unique ID used for menu_slug.
*
* @var string
*/
public $id = null;
/**
* The text to be displayed in the title tags of the page.
*
* @var string
*/
public $title = null;
/**
* The slug name for the parent menu.
*
* @var string
*/
public $parent = null;
/**
* The The on-screen name text for the menu.
*
* @var string
*/
public $menu_title = null;
/**
* The capability required for this menu to be displayed to the user.
*
* @var string
*/
public $capability = 'manage_options';
/**
* The icon for this menu.
*
* @var string
*/
public $icon = 'dashicons-art';
/**
* The position in the menu order this menu should appear.
*
* @var int
*/
public $position = -1;
/**
* The init hook priority.
*
* @var int
*/
public $priority = 25;
/**
* The function/file that displays the page content for the menu page.
*
* @var string|callable
*/
public $render = null;
/**
* The function that run on page POST to save data.
*
* @var callable
*/
public $onsave = null;
/**
* Hold contextual help tabs.
*
* @var array
*/
public $help = null;
/**
* Hold scripts and styles.
*
* @var array
*/
public $assets = null;
/**
* Check if plugin is network active.
*
* @var array
*/
public $is_network = false;
/**
* Hold classes for body tag.
*
* @var array
*/
public $classes = null;
/**
* Hold localized data.
*
* @var array
*/
public $json = null;
/**
* The Constructor.
*
* @param string $id Admin page unique id.
* @param string $title Title of the admin page.
* @param array $config Optional. Override page settings.
*/
public function __construct( $id, $title, $config = [] ) {
// Early bail!
if ( ! $id ) {
wp_die( esc_html__( '$id variable required', 'seo-by-rank-math' ), esc_html__( 'Variable Required', 'seo-by-rank-math' ) );
}
if ( ! $title ) {
wp_die( esc_html__( '$title variable required', 'seo-by-rank-math' ), esc_html__( 'Variable Required', 'seo-by-rank-math' ) );
}
$this->id = $id;
$this->title = $title;
foreach ( $config as $key => $value ) {
$this->$key = $value;
}
if ( ! $this->menu_title ) {
$this->menu_title = $title;
}
add_action( 'init', [ $this, 'init' ], $this->priority ?? 25 );
}
/**
* Init admin page when WordPress Initialises.
*
* @codeCoverageIgnore
*/
public function init() {
$priority = $this->parent ? intval( $this->position ) : -1;
add_action( $this->is_network ? 'network_admin_menu' : 'admin_menu', [ $this, 'register_menu' ], $priority );
// If not the page is not this page stop here.
if ( ! $this->is_current_page() ) {
return;
}
$hooks = [
'admin_init' => [
'callback' => 'save',
'condition' => ! is_null( $this->onsave ) && is_callable( $this->onsave ),
],
'admin_enqueue_scripts' => [
'callback' => 'enqueue',
'condition' => ! empty( $this->assets ),
],
'admin_head' => [
'callback' => 'contextual_help',
'condition' => ! empty( $this->help ),
],
'admin_body_class' => [
'callback' => 'body_class',
'condition' => ! empty( $this->classes ),
],
];
foreach ( $hooks as $hook => $data ) {
if ( true === $data['condition'] ) {
add_action( $hook, [ $this, $data['callback'] ] );
}
}
}
/**
* Register Admin Menu.
*
* @codeCoverageIgnore
*/
public function register_menu() {
if ( ! $this->parent ) {
add_menu_page( $this->title, $this->menu_title, $this->capability, $this->id, [ $this, 'display' ], $this->icon, $this->position );
return;
}
add_submenu_page( $this->parent, $this->title, $this->menu_title, $this->capability, $this->id, [ $this, 'display' ] );
}
/**
* Enqueue styles and scripts.
*
* @codeCoverageIgnore
*/
public function enqueue() {
$this->enqueue_styles();
$this->enqueue_scripts();
$this->add_localized_data();
}
/**
* Add classes to <body> of WordPress admin.
*
* @codeCoverageIgnore
*
* @param string $classes Space-separated list of CSS classes.
*
* @return string
*/
public function body_class( $classes = '' ) {
return $classes . ' ' . join( ' ', $this->classes );
}
/**
* Save anything you want using onsave function.
*
* @codeCoverageIgnore
*/
public function save() {
call_user_func( $this->onsave, $this );
}
/**
* Contextual Help.
*
* @codeCoverageIgnore
*/
public function contextual_help() {
$screen = get_current_screen();
foreach ( $this->help as $tab_id => $tab ) {
$tab['id'] = $tab_id;
$tab['content'] = $this->get_help_content( $tab );
$screen->add_help_tab( $tab );
}
}
/**
* Render admin page content using render function you passed in config.
*
* @codeCoverageIgnore
*/
public function display() {
if ( is_null( $this->render ) ) {
return;
}
if ( 'settings' === $this->render ) {
return $this->display_settings();
}
if ( is_callable( $this->render ) ) {
call_user_func( $this->render, $this );
return;
}
if ( is_string( $this->render ) ) {
include_once $this->render;
}
}
/**
* Is the page is current page.
*
* @return bool
*/
public function is_current_page() {
return Param::get( 'page' ) === $this->id;
}
/**
* Enqueue styles
*
* @codeCoverageIgnore
*/
private function enqueue_styles() {
if ( ! isset( $this->assets['styles'] ) || empty( $this->assets['styles'] ) ) {
return;
}
foreach ( $this->assets['styles'] as $handle => $src ) {
wp_enqueue_style( $handle, $src, null, rank_math()->version );
}
}
/**
* Enqueue scripts.
*
* @codeCoverageIgnore
*/
private function enqueue_scripts() {
if ( ! isset( $this->assets['scripts'] ) || empty( $this->assets['scripts'] ) ) {
return;
}
foreach ( $this->assets['scripts'] as $handle => $src ) {
if ( $handle === 'media-editor' ) {
wp_enqueue_media();
}
wp_enqueue_script( $handle, $src, null, rank_math()->version, true );
}
do_action( 'rank-math/admin_enqueue_scripts' );
}
/**
* Get tab content
*
* @codeCoverageIgnore
*
* @param array $tab Tab to get content for.
*
* @return string
*/
private function get_help_content( $tab ) {
ob_start();
// If it is a function.
if ( isset( $tab['content'] ) && is_callable( $tab['content'] ) ) {
call_user_func( $tab['content'] );
}
// If it is a file.
if ( isset( $tab['view'] ) && $tab['view'] ) {
require $tab['view'];
}
return ob_get_clean();
}
/**
* Localized data.
*/
private function add_localized_data() {
if ( empty( $this->assets['json'] ) ) {
return;
}
foreach ( $this->assets['json'] as $key => $value ) {
Helper::add_json( $key, $value );
}
Helper::add_json(
'settings',
[
'general' => Helper::get_settings( 'general' ),
'titles' => Helper::get_settings( 'titles' ),
'sitemap' => Helper::get_settings( 'sitemap' ),
]
);
}
/**
* Display settings.
*/
private function display_settings() {
echo '<div id="rank-math-settings" class="' . esc_attr( $this->id ) . '"></div>';
}
}
@@ -0,0 +1,574 @@
<?php
/**
* The admin post columns functionality.
*
* @since 0.9.0
* @package RankMath
* @subpackage RankMath\Admin
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\Admin;
use RankMath\Helper;
use RankMath\Helpers\Str;
use RankMath\Helpers\Param;
use RankMath\Runner;
use RankMath\Traits\Hooker;
use RankMath\Admin\Database\Database;
defined( 'ABSPATH' ) || exit;
/**
* Post_Columns class.
*/
class Post_Columns implements Runner {
use Hooker;
/**
* SEO data.
*
* @var array
*/
private $data = [];
/**
* Register hooks.
*/
public function hooks() {
$this->action( 'admin_init', 'init' );
}
/**
* Initialize.
*/
public function init() {
if ( ! Helper::has_cap( 'onpage_general' ) ) {
return;
}
$this->register_post_columns();
$this->register_media_columns();
$this->register_taxonomy_columns();
// Column Content.
$this->filter( 'rank_math_title', 'get_column_title', 5, 2 );
$this->filter( 'rank_math_description', 'get_column_description', 5, 2 );
$this->filter( 'rank_math_seo_details', 'get_column_seo_details', 5 );
}
/**
* Register post column hooks.
*/
private function register_post_columns() {
$post_types = Helper::get_allowed_post_types();
foreach ( $post_types as $post_type ) {
$this->filter( 'edd_download_columns', 'add_columns', 11 );
$this->filter( "manage_{$post_type}_posts_columns", 'add_columns', 11 );
$this->action( "manage_{$post_type}_posts_custom_column", 'columns_contents', 11, 2 );
$this->filter( "manage_edit-{$post_type}_sortable_columns", 'sortable_columns', 11 );
// Also make them hidden by default.
$user_id = get_current_user_id();
$columns_hidden = (array) get_user_meta( $user_id, "manageedit-{$post_type}columnshidden", true );
$maybe_hidden = get_user_meta( $user_id, "manageedit-{$post_type}columnshidden_default", true );
// Continue if default is already set.
if ( $maybe_hidden ) {
continue;
}
// Set it to hidden by default.
$columns_hidden = array_unique( array_merge( $columns_hidden, [ 'rank_math_title', 'rank_math_description' ] ) );
update_user_meta( $user_id, "manageedit-{$post_type}columnshidden", $columns_hidden );
update_user_meta( $user_id, "manageedit-{$post_type}columnshidden_default", '1' );
}
}
/**
* Register media column hooks.
*/
private function register_media_columns() {
if ( ! Helper::get_settings( 'titles.pt_attachment_bulk_editing' ) ) {
return;
}
$this->filter( 'manage_media_columns', 'add_media_columns', 11 );
$this->action( 'manage_media_custom_column', 'media_contents', 11, 2 );
}
/**
* Register taxonomy columns hooks.
*
* @return void
*/
private function register_taxonomy_columns() {
$taxonomies = Helper::get_allowed_taxonomies();
foreach ( $taxonomies as $taxonomy ) {
$this->filter( "manage_edit-{$taxonomy}_columns", 'add_taxonomy_columns', 9 );
$this->filter( "manage_{$taxonomy}_custom_column", 'taxonomy_columns_contents', 10, 3 );
}
}
/**
* Add new columns for SEO title, description and focus keywords.
*
* @param array $columns Array of column names.
*
* @return array
*/
public function add_columns( $columns ) {
global $post_type;
$current_pt = $post_type;
if ( ! $post_type && 'inline-save' === Param::post( 'action' ) ) {
$post_id = Param::post( 'post_ID', 0, FILTER_VALIDATE_INT );
$current_pt = get_post_type( $post_id );
}
$columns['rank_math_seo_details'] = esc_html__( 'SEO Details', 'seo-by-rank-math' );
if ( Helper::get_settings( 'titles.pt_' . $current_pt . '_bulk_editing', true ) ) {
$columns['rank_math_title'] = esc_html__( 'SEO Title', 'seo-by-rank-math' );
$columns['rank_math_description'] = esc_html__( 'SEO Desc', 'seo-by-rank-math' );
}
return $columns;
}
/**
* Make the SEO Score column sortable.
*
* @param array $columns Array of column names.
*
* @return array
*/
public function sortable_columns( $columns ) {
$columns['rank_math_seo_details'] = 'rank_math_seo_score';
return $columns;
}
/**
* Add new columns for Media Alt & Title.
*
* @param array $columns Array of column names.
*
* @return array
*/
public function add_media_columns( $columns ) {
$columns['rank_math_image_title'] = esc_html__( 'Title', 'seo-by-rank-math' );
$columns['rank_math_image_alt'] = esc_html__( 'Alternative Text', 'seo-by-rank-math' );
return $columns;
}
/**
* Adds custom columns to taxonomy list view.
*
* @param array $columns Columns belonging to current taxonomy.
*
* @return array
*/
public function add_taxonomy_columns( $columns ) {
$screen = get_current_screen();
if ( ! $screen || empty( $screen->taxonomy ) ) {
return $columns;
}
if ( Helper::get_settings( 'titles.tax_' . $screen->taxonomy . '_bulk_editing', false ) ) {
$columns['rank_math_title'] = esc_html__( 'SEO Title', 'seo-by-rank-math' );
$columns['rank_math_description'] = esc_html__( 'SEO Desc', 'seo-by-rank-math' );
}
return $columns;
}
/**
* Add content for custom column.
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
public function columns_contents( $column_name, $post_id ) {
if ( Str::starts_with( 'rank_math', $column_name ) ) {
do_action( $column_name, $post_id );
}
}
/**
* Generate content of custom columns.
*
* @param string $content The content of the current column.
* @param string $column_name The column name.
* @param int $term_id The unique ID of the current term.
*
* @return string
*/
public function taxonomy_columns_contents( $content, $column_name, $term_id ) {
if ( Str::starts_with( 'rank_math_', $column_name ) ) {
do_action( $column_name, $term_id, 'term' );
}
return $content;
}
/**
* Add content for title column.
*
* @param int $object_id The current Object ID.
* @param string $object_type The current Object type.
*/
public function get_column_title( $object_id, $object_type = 'post' ) {
if ( empty( $this->data ) ) {
$method = "get_{$object_type}_seo_data";
$this->$method( $object_type );
}
$title = ! empty( $this->data[ $object_id ]['rank_math_title'] ) ? $this->data[ $object_id ]['rank_math_title'] : '';
if ( ! $title ) {
$title = $this->get_default_title( $object_id, $object_type );
}
?>
<span class="rank-math-column-display"><?php echo esc_html( $title ); ?></span>
<textarea class="rank-math-column-value" data-field="title" tabindex="11"><?php echo esc_attr( $title ); ?></textarea>
<div class="rank-math-column-edit">
<a href="#" class="rank-math-column-save"><?php esc_html_e( 'Save', 'seo-by-rank-math' ); ?></a>
<a href="#" class="button-link-delete rank-math-column-cancel"><?php esc_html_e( 'Cancel', 'seo-by-rank-math' ); ?></a>
</div>
<?php
}
/**
* Add content for description column.
*
* @param int $object_id The current Object ID.
* @param string $object_type The current Object type.
*/
public function get_column_description( $object_id, $object_type = 'post' ) {
$description = ! empty( $this->data[ $object_id ]['rank_math_description'] ) ? $this->data[ $object_id ]['rank_math_description'] : '';
if ( ! $description ) {
$description = $this->get_default_description( $object_id, $object_type );
}
?>
<span class="rank-math-column-display"><?php echo esc_html( $description ); ?></span>
<textarea class="rank-math-column-value" data-field="description" tabindex="11"><?php echo esc_attr( $description ); ?></textarea>
<div class="rank-math-column-edit">
<a href="#" class="rank-math-column-save"><?php esc_html_e( 'Save', 'seo-by-rank-math' ); ?></a>
<a href="#" class="button-link-delete rank-math-column-cancel"><?php esc_html_e( 'Cancel', 'seo-by-rank-math' ); ?></a>
</div>
<?php
}
/**
* Add content for title column.
*
* @param int $post_id The current post ID.
*/
public function get_column_seo_details( $post_id ) {
if ( empty( $this->data ) ) {
$this->get_post_seo_data();
}
$data = isset( $this->data[ $post_id ] ) ? $this->data[ $post_id ] : [];
if ( ! self::is_post_indexable( $post_id ) ) {
echo '<span class="rank-math-column-display seo-score no-score "><strong>N/A</strong></span>';
echo '<strong>' . esc_html__( 'No Index', 'seo-by-rank-math' ) . '</strong>';
$this->do_action( 'post/column/seo_details', $post_id, $data, $this->data );
return;
}
$keyword = ! empty( $data['rank_math_focus_keyword'] ) ? $data['rank_math_focus_keyword'] : '';
$keyword = explode( ',', $keyword )[0];
$is_pillar = ! empty( $data['rank_math_pillar_content'] ) && 'on' === $data['rank_math_pillar_content'] ? true : false;
$score = empty( $keyword ) ? false : $this->get_seo_score( $data );
$class = ! $score ? 'no-score' : $this->get_seo_score_class( $score );
$score = $score ? $score . ' / 100' : 'N/A';
?>
<span class="rank-math-column-display seo-score <?php echo esc_attr( $class ); ?> <?php echo ! $score ? 'disabled' : ''; ?>">
<strong><?php echo esc_html( $score ); ?></strong>
<?php if ( $is_pillar ) { ?>
<img class="is-pillar" src="<?php echo esc_url( rank_math()->plugin_url() . 'assets/admin/img/pillar.svg' ); ?>" alt="<?php esc_html_e( 'Is Pillar', 'seo-by-rank-math' ); ?>" title="<?php esc_html_e( 'Is Pillar', 'seo-by-rank-math' ); ?>" width="25" />
<?php } ?>
</span>
<label><?php esc_html_e( 'Focus Keyword', 'seo-by-rank-math' ); ?>:</label>
<span class="rank-math-column-display">
<strong title="Focus Keyword"><?php esc_html_e( 'Keyword', 'seo-by-rank-math' ); ?>:</strong>
<span>
<?php
echo $keyword ? wp_kses_post( $this->do_filter( 'post/column/seo_details/focus_keyword', $keyword ) ) : esc_html__( 'Not Set', 'seo-by-rank-math' );
?>
</span>
</span>
<input class="rank-math-column-value" data-field="focus_keyword" tabindex="11" value="<?php echo esc_attr( $keyword ); ?>" />
<?php $this->do_action( 'post/column/seo_details', $post_id, $data, $this->data ); ?>
<div class="rank-math-column-edit">
<a href="#" class="rank-math-column-save"><?php esc_html_e( 'Save', 'seo-by-rank-math' ); ?></a>
<a href="#" class="button-link-delete rank-math-column-cancel"><?php esc_html_e( 'Cancel', 'seo-by-rank-math' ); ?></a>
</div>
<?php
}
/**
* Add content for custom media column.
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
public function media_contents( $column_name, $post_id ) {
if ( 'rank_math_image_title' === $column_name ) {
$title = get_the_title( $post_id );
?>
<span class="rank-math-column-display"><?php echo esc_html( $title ); ?></span>
<input class="rank-math-column-value" data-field="image_title" tabindex="11" value="<?php echo esc_attr( $title ); ?>" />
<div class="rank-math-column-edit">
<a href="#" class="rank-math-column-save"><?php esc_html_e( 'Save', 'seo-by-rank-math' ); ?></a>
<a href="#" class="button-link-delete rank-math-column-cancel"><?php esc_html_e( 'Cancel', 'seo-by-rank-math' ); ?></a>
</div>
<?php
return;
}
if ( 'rank_math_image_alt' === $column_name ) {
$alt = get_post_meta( $post_id, '_wp_attachment_image_alt', true );
?>
<span class="rank-math-column-display"><?php echo esc_html( $alt ); ?></span>
<input class="rank-math-column-value" data-field="image_alt" tabindex="11" value="<?php echo esc_attr( $alt ); ?>" />
<div class="rank-math-column-edit">
<a href="#" class="rank-math-column-save"><?php esc_html_e( 'Save', 'seo-by-rank-math' ); ?></a>
<a href="#" class="button-link-delete rank-math-column-cancel"><?php esc_html_e( 'Cancel', 'seo-by-rank-math' ); ?></a>
</div>
<?php
return;
}
}
/**
* Get Default title for the object type.
*
* @param int $object_id The current Object ID.
* @param string $object_type The current Object type.
*/
private function get_default_title( $object_id, $object_type ) {
if ( $object_type === 'term' ) {
$term = get_term( $object_id );
return Helper::get_settings( "titles.tax_{$term->taxonomy}_title" );
}
$post_type = get_post_type( $object_id );
return Helper::get_settings( "titles.pt_{$post_type}_title" );
}
/**
* Get Default description for the object type.
*
* @param int $object_id The current Object ID.
* @param string $object_type The current Object type.
*/
private function get_default_description( $object_id, $object_type ) {
if ( $object_type === 'term' ) {
$term = get_term( $object_id );
return Helper::get_settings( "titles.tax_{$term->taxonomy}_description" );
}
$post_type = get_post_type( $object_id );
return has_excerpt( $object_id ) ? '%excerpt%' : Helper::get_settings( "titles.pt_{$post_type}_description" );
}
/**
* Get Terms SEO data.
*/
private function get_term_seo_data() {
$wp_list_table = _get_list_table( 'WP_Terms_List_Table' );
$wp_list_table->prepare_items();
$items = $wp_list_table->items;
if ( empty( $items ) ) {
return false;
}
$term_ids = array_filter(
array_map(
function ( $item ) {
return isset( $item->term_id ) ? $item->term_id : '';
},
$items
)
);
$results = Database::table( 'termmeta' )->select( [ 'term_id', 'meta_key', 'meta_value' ] )->whereIn( 'term_id', $term_ids )->whereLike( 'meta_key', 'rank_math' )->get( ARRAY_A );
if ( empty( $results ) ) {
return false;
}
foreach ( $results as $result ) {
$this->data[ $result['term_id'] ][ $result['meta_key'] ] = $result['meta_value'];
}
}
/**
* Get Post SEO data.
*/
private function get_post_seo_data() {
$post_ids = [];
$post_ids = array_filter( $this->get_post_ids() );
$post_id = (int) Param::post( 'post_ID' );
if ( $post_id ) {
$post_ids[] = $post_id;
}
if ( empty( $post_ids ) ) {
return false;
}
$results = Database::table( 'postmeta' )->select( [ 'post_id', 'meta_key', 'meta_value' ] )->whereIn( 'post_id', $post_ids )->whereLike( 'meta_key', 'rank_math' )->get( ARRAY_A );
if ( empty( $results ) ) {
return false;
}
foreach ( $results as $result ) {
$this->data[ $result['post_id'] ][ $result['meta_key'] ] = $result['meta_value'];
}
}
/**
* Get Post IDs displayed on the Post lists page.
*/
private function get_post_ids() {
global $wp_query, $per_page;
if ( empty( $wp_query->posts ) ) {
return [];
}
$pages = $wp_query->posts;
if (
! is_post_type_hierarchical( Param::get( 'post_type' ) ) ||
'menu_order title' !== $wp_query->query['orderby']
) {
return array_map(
function ( $post ) {
return isset( $post->ID ) ? $post->ID : '';
},
$pages
);
}
$children_pages = [];
if ( empty( Param::request( 's' ) ) ) {
$top_level_pages = [];
foreach ( $pages as $page ) {
if ( $page->post_parent > 0 ) {
$children_pages[ $page->post_parent ][] = $page;
} else {
$top_level_pages[] = $page;
}
}
$pages = &$top_level_pages;
}
$pagenum = max( 1, Param::request( 'paged', 0 ) );
$count = 0;
$start = ( $pagenum - 1 ) * $per_page;
$end = $start + $per_page;
$ids = [];
foreach ( $pages as $page ) {
if ( $count >= $end ) {
break;
}
if ( $count >= $start ) {
$ids[] = $page->ID;
}
++$count;
$this->add_child_page_ids( $children_pages, $page->ID, $ids, $count );
}
return $ids;
}
/**
* Add the child page IDs to the list of IDs to be processed.
*
* @param array $children_pages Child Pages.
* @param int $id Current page ID.
* @param array $ids IDs to be processed.
* @param int $count Counter.
*/
private function add_child_page_ids( $children_pages, $id, &$ids, &$count ) {
if ( empty( $children_pages ) || empty( $children_pages[ $id ] ) ) {
return;
}
foreach ( $children_pages[ $id ] as $child_page ) {
$id = $child_page->ID;
$ids[] = $child_page->ID;
++$count;
$this->add_child_page_ids( $children_pages, $id, $ids, $count );
}
}
/**
* Get SEO score.
*
* @param array $data SEO data of current post.
*
* @return string
*/
private function get_seo_score( $data ) {
if ( ! isset( $data['rank_math_seo_score'] ) ) {
return false;
}
if ( ! Helper::is_score_enabled() ) {
return false;
}
return $data['rank_math_seo_score'] ? $data['rank_math_seo_score'] : 0;
}
/**
* Get SEO score rating string: great/good/bad.
*
* @param int $score Score.
*
* @return string
*/
private function get_seo_score_class( $score ) {
if ( $score > 80 ) {
return 'great';
}
if ( $score > 50 && $score < 81 ) {
return 'good';
}
return 'bad';
}
/**
* Check post indexable status.
*
* @param int $post_id Post ID.
*/
public static function is_post_indexable( $post_id ) {
$robots = Param::post( 'rank_math_robots', false, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
$robots = apply_filters( 'rank_math/admin/robots', $robots, $post_id );
if ( ! empty( $robots ) ) {
return in_array( 'index', $robots, true ) ? true : false;
}
return Helper::is_post_indexable( $post_id, false );
}
}

Some files were not shown because too many files have changed in this diff Show More