Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 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;
}
}