Initial commit xmarticaims
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
/**
|
||||
* The Links module admin page registration.
|
||||
*
|
||||
* @since 1.0.266
|
||||
* @package RankMath
|
||||
* @subpackage RankMath\Links\Admin
|
||||
* @author Rank Math <support@rankmath.com>
|
||||
*/
|
||||
|
||||
namespace RankMath\Links\Admin;
|
||||
|
||||
use RankMath\Helper;
|
||||
use RankMath\Traits\Hooker;
|
||||
use RankMath\Admin\Page;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Admin class.
|
||||
*/
|
||||
class Admin {
|
||||
|
||||
use Hooker;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->filter( 'rank_math/admin_pages', 'add_links_page' );
|
||||
$this->action( 'init', 'register_admin_page' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add Links page to Rank Math admin menu.
|
||||
*
|
||||
* @param array $pages Existing pages.
|
||||
* @return array
|
||||
*/
|
||||
public function add_links_page( $pages ) {
|
||||
$pages[] = 'rank-math_page_rank-math-links-page';
|
||||
return $pages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register admin page.
|
||||
*/
|
||||
public function register_admin_page() {
|
||||
new Page(
|
||||
'rank-math-links-page',
|
||||
esc_html__( 'AI Link Genius', 'seo-by-rank-math' ),
|
||||
[
|
||||
'position' => 4,
|
||||
'parent' => 'rank-math',
|
||||
'menu_title' => esc_html__( 'AI Link Genius', 'seo-by-rank-math' ),
|
||||
'capability' => 'rank_math_link_builder',
|
||||
'render' => function () {
|
||||
echo '<div id="rank-math-links-page-container"></div>';
|
||||
},
|
||||
'classes' => [ 'rank-math-page' ],
|
||||
'assets' => [
|
||||
'styles' => [
|
||||
'rank-math-common' => '',
|
||||
],
|
||||
'scripts' => [
|
||||
'lodash' => '',
|
||||
'wp-components' => '',
|
||||
'wp-element' => '',
|
||||
'rank-math-components' => '',
|
||||
'rank-math-links-page' => RANK_MATH_URL . 'includes/modules/links/assets/js/links-page.js',
|
||||
],
|
||||
'json' => [
|
||||
'links' => [
|
||||
'postTypes' => Helper::choices_post_types(),
|
||||
'imagesUrl' => RANK_MATH_URL . 'includes/modules/links/assets/images/',
|
||||
],
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
/**
|
||||
* Fires after the Links admin page is registered.
|
||||
*
|
||||
* PRO plugin (Link Genius) hooks here to dequeue the Free bundle
|
||||
* and enqueue its own full-featured React app instead.
|
||||
*
|
||||
* @since 1.0.266
|
||||
*/
|
||||
do_action( 'rank_math/links/admin_page_registered' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,828 @@
|
||||
<?php
|
||||
/**
|
||||
* Links REST API controller.
|
||||
*
|
||||
* Handles links-related endpoints for the Free plugin admin page:
|
||||
* /posts, /posts-stats, /links, /links-stats.
|
||||
*
|
||||
* @since 1.0.266
|
||||
* @package RankMath
|
||||
* @subpackage RankMath\Links\Api
|
||||
* @author Rank Math <support@rankmath.com>
|
||||
*/
|
||||
|
||||
namespace RankMath\Links\Api;
|
||||
|
||||
use WP_REST_Server;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use RankMath\Helper;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Controller class.
|
||||
*
|
||||
* Provides REST endpoints for basic links and posts data using
|
||||
* only Free plugin tables (rank_math_internal_meta, rank_math_internal_links).
|
||||
* PRO plugin can override responses via filters to supply richer data.
|
||||
*/
|
||||
class Controller {
|
||||
|
||||
/**
|
||||
* REST API namespace.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const NAMESPACE = 'rankmath/v1';
|
||||
|
||||
/**
|
||||
* Cache group for object caching.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const CACHE_GROUP = 'rank_math_links';
|
||||
|
||||
/**
|
||||
* Cache TTL in seconds (30 minutes).
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
const CACHE_TTL = 1800;
|
||||
|
||||
/**
|
||||
* Register REST API routes.
|
||||
*/
|
||||
public function register_routes() {
|
||||
// GET /rankmath/v1/links/posts.
|
||||
register_rest_route(
|
||||
self::NAMESPACE,
|
||||
'/links/posts',
|
||||
[
|
||||
'methods' => WP_REST_Server::READABLE,
|
||||
'callback' => [ $this, 'get_posts' ],
|
||||
'permission_callback' => [ $this, 'check_permission' ],
|
||||
'args' => $this->get_posts_args(),
|
||||
]
|
||||
);
|
||||
|
||||
// GET /rankmath/v1/links/posts-stats.
|
||||
register_rest_route(
|
||||
self::NAMESPACE,
|
||||
'/links/posts-stats',
|
||||
[
|
||||
'methods' => WP_REST_Server::READABLE,
|
||||
'callback' => [ $this, 'get_posts_stats' ],
|
||||
'permission_callback' => [ $this, 'check_permission' ],
|
||||
]
|
||||
);
|
||||
|
||||
// GET /rankmath/v1/links/links.
|
||||
register_rest_route(
|
||||
self::NAMESPACE,
|
||||
'/links/links',
|
||||
[
|
||||
'methods' => WP_REST_Server::READABLE,
|
||||
'callback' => [ $this, 'get_links' ],
|
||||
'permission_callback' => [ $this, 'check_permission' ],
|
||||
'args' => $this->get_links_args(),
|
||||
]
|
||||
);
|
||||
|
||||
// GET /rankmath/v1/links/links-stats.
|
||||
register_rest_route(
|
||||
self::NAMESPACE,
|
||||
'/links/links-stats',
|
||||
[
|
||||
'methods' => WP_REST_Server::READABLE,
|
||||
'callback' => [ $this, 'get_links_stats' ],
|
||||
'permission_callback' => [ $this, 'check_permission' ],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission callback: require manage_options capability.
|
||||
*
|
||||
* @return bool|\WP_Error
|
||||
*/
|
||||
public function check_permission() {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return new \WP_Error(
|
||||
'rest_forbidden',
|
||||
esc_html__( 'You do not have permission to access this resource.', 'seo-by-rank-math' ),
|
||||
[ 'status' => rest_authorization_required_code() ]
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get posts with link metrics.
|
||||
*
|
||||
* @param WP_REST_Request $request Request.
|
||||
* @return WP_REST_Response
|
||||
*/
|
||||
public function get_posts( $request ) {
|
||||
$data = $this->get_posts_data(
|
||||
[
|
||||
'page' => $request->get_param( 'page' ),
|
||||
'per_page' => $request->get_param( 'per_page' ),
|
||||
'search' => $request->get_param( 'search' ),
|
||||
'post_type' => $request->get_param( 'post_type' ),
|
||||
'is_orphan' => $request->get_param( 'is_orphan' ),
|
||||
'seo_score_range' => $request->get_param( 'seo_score_range' ),
|
||||
'post_id' => $request->get_param( 'post_id' ),
|
||||
'orderby' => $request->get_param( 'orderby' ),
|
||||
'order' => $request->get_param( 'order' ),
|
||||
]
|
||||
);
|
||||
|
||||
return rest_ensure_response( $data );
|
||||
}
|
||||
|
||||
/**
|
||||
* Query post link stats and return the data array.
|
||||
*
|
||||
* Shared by the REST endpoint and the Abilities API so neither needs to
|
||||
* construct a WP_REST_Request. The REST endpoint wraps the return value
|
||||
* in rest_ensure_response(); abilities call this method directly.
|
||||
*
|
||||
* @param array $args {
|
||||
* Raw or pre-sanitized query arguments.
|
||||
*
|
||||
* @type int $page 1-based page number. Default 1.
|
||||
* @type int $per_page Rows per page (max 100). Default 50.
|
||||
* @type string $search Partial post-title search. Default ''.
|
||||
* @type array $post_type Allowed post types. Default [].
|
||||
* @type string $is_orphan Orphan filter: 'orphan', 'linked', or ''. Default ''.
|
||||
* @type string $seo_score_range SEO score filter: great, good, bad, no-score, or ''. Default ''.
|
||||
* @type int $post_id Filter to a single post by ID. Default 0.
|
||||
* @type string $orderby Order-by field. Default 'post_title'.
|
||||
* @type string $order Sort direction: ASC or DESC. Default 'ASC'.
|
||||
* }
|
||||
* @return array { posts: array, total: int, pages: int }
|
||||
*/
|
||||
public function get_posts_data( array $args ): array {
|
||||
$page = max( 1, (int) ( $args['page'] ?? 1 ) );
|
||||
$per_page = min( 100, max( 1, (int) ( $args['per_page'] ?? 50 ) ) );
|
||||
$offset = ( $page - 1 ) * $per_page;
|
||||
|
||||
$normalized = [
|
||||
'search' => sanitize_text_field( (string) ( $args['search'] ?? '' ) ),
|
||||
'post_type' => (array) ( $args['post_type'] ?? [] ),
|
||||
'is_orphan' => sanitize_text_field( (string) ( $args['is_orphan'] ?? '' ) ),
|
||||
'seo_score_range' => sanitize_text_field( (string) ( $args['seo_score_range'] ?? '' ) ),
|
||||
'post_id' => absint( $args['post_id'] ?? 0 ),
|
||||
'orderby' => sanitize_text_field( (string) ( $args['orderby'] ?? 'post_title' ) ),
|
||||
'order' => sanitize_text_field( (string) ( $args['order'] ?? 'ASC' ) ),
|
||||
'offset' => $offset,
|
||||
'per_page' => $per_page,
|
||||
];
|
||||
|
||||
/**
|
||||
* Filter to allow overriding the posts REST response.
|
||||
*
|
||||
* Return a non-null array to bypass the Free plugin's query entirely.
|
||||
* Expected format: [ 'posts' => array, 'total' => int, 'pages' => int ]
|
||||
*
|
||||
* @since 1.0.266
|
||||
*
|
||||
* @param null|array $override Return override data or null to use Free's query.
|
||||
* @param array $normalized Normalized query arguments.
|
||||
*/
|
||||
$override = apply_filters( 'rank_math/links/rest_posts_response', null, $normalized );
|
||||
if ( null !== $override ) {
|
||||
return (array) $override;
|
||||
}
|
||||
|
||||
$results = $this->query_posts( $normalized );
|
||||
$total = $this->query_posts_count( $normalized );
|
||||
|
||||
return [
|
||||
'posts' => $results,
|
||||
'total' => (int) $total,
|
||||
'pages' => (int) ceil( $total / $per_page ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get aggregate posts statistics.
|
||||
*
|
||||
* @return WP_REST_Response
|
||||
*/
|
||||
public function get_posts_stats() {
|
||||
/**
|
||||
* Filter to allow overriding the posts-stats REST response.
|
||||
*
|
||||
* @since 1.0.266
|
||||
*
|
||||
* @param null|array $override Return override data or null to use Free's query.
|
||||
*/
|
||||
$override = apply_filters( 'rank_math/links/rest_posts_stats_response', null );
|
||||
if ( null !== $override ) {
|
||||
return rest_ensure_response( $override );
|
||||
}
|
||||
|
||||
$cache_key = 'posts_stats';
|
||||
$cached = wp_cache_get( $cache_key, self::CACHE_GROUP );
|
||||
if ( false !== $cached ) {
|
||||
return rest_ensure_response( $cached );
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
|
||||
$stats = $wpdb->get_row(
|
||||
"SELECT
|
||||
COUNT(DISTINCT m.object_id) as total_posts,
|
||||
SUM(CASE WHEN m.incoming_link_count IS NULL OR m.incoming_link_count = 0 THEN 1 ELSE 0 END) as orphan_posts,
|
||||
SUM(CASE WHEN m.internal_link_count > 0 THEN 1 ELSE 0 END) as posts_with_internal,
|
||||
SUM(CASE WHEN m.external_link_count > 0 THEN 1 ELSE 0 END) as posts_with_external
|
||||
FROM {$wpdb->prefix}rank_math_internal_meta m
|
||||
INNER JOIN {$wpdb->posts} p ON m.object_id = p.ID
|
||||
WHERE p.post_status = 'publish'"
|
||||
);
|
||||
|
||||
$response = [
|
||||
'total_posts' => (int) ( $stats->total_posts ?? 0 ),
|
||||
'orphan_posts' => (int) ( $stats->orphan_posts ?? 0 ),
|
||||
'posts_with_internal' => (int) ( $stats->posts_with_internal ?? 0 ),
|
||||
'posts_with_external' => (int) ( $stats->posts_with_external ?? 0 ),
|
||||
];
|
||||
|
||||
wp_cache_set( $cache_key, $response, self::CACHE_GROUP, self::CACHE_TTL );
|
||||
|
||||
return rest_ensure_response( $response );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get links with basic columns.
|
||||
*
|
||||
* @param WP_REST_Request $request Request.
|
||||
* @return WP_REST_Response
|
||||
*/
|
||||
public function get_links( $request ) {
|
||||
return rest_ensure_response(
|
||||
$this->get_links_data(
|
||||
[
|
||||
'page' => $request->get_param( 'page' ),
|
||||
'per_page' => $request->get_param( 'per_page' ),
|
||||
'search' => $request->get_param( 'search' ),
|
||||
'source_id' => $request->get_param( 'source_id' ),
|
||||
'target_post_id' => $request->get_param( 'target_post_id' ),
|
||||
'is_internal' => $request->get_param( 'is_internal' ),
|
||||
'orderby' => $request->get_param( 'orderby' ),
|
||||
'order' => $request->get_param( 'order' ),
|
||||
]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch and normalize link rows without REST plumbing.
|
||||
*
|
||||
* Shared by the REST endpoint and the Abilities API runner so neither
|
||||
* needs to construct a WP_REST_Request object.
|
||||
*
|
||||
* @param array $args {
|
||||
* Query arguments (all optional).
|
||||
*
|
||||
* @type int $page 1-based page number (default 1).
|
||||
* @type int $per_page Rows per page, capped at 100 (default 50).
|
||||
* @type string $search URL search string.
|
||||
* @type int $source_id Source post ID.
|
||||
* @type int $target_post_id Target post ID.
|
||||
* @type string $is_internal '1' = internal only, '0' = external only, '' = all.
|
||||
* @type string $orderby Column to sort by.
|
||||
* @type string $order Sort direction.
|
||||
* }
|
||||
* @return array { links: array, total: int, pages: int }
|
||||
*/
|
||||
public function get_links_data( array $args ): array {
|
||||
$page = max( 1, (int) ( $args['page'] ?? 1 ) );
|
||||
$per_page = min( 100, max( 1, (int) ( $args['per_page'] ?? 50 ) ) );
|
||||
$offset = ( $page - 1 ) * $per_page;
|
||||
|
||||
$normalized = [
|
||||
'search' => sanitize_text_field( (string) ( $args['search'] ?? '' ) ),
|
||||
'source_id' => absint( $args['source_id'] ?? 0 ),
|
||||
'target_post_id' => absint( $args['target_post_id'] ?? 0 ),
|
||||
'is_internal' => sanitize_text_field( (string) ( $args['is_internal'] ?? '' ) ),
|
||||
'orderby' => sanitize_text_field( (string) ( $args['orderby'] ?? '' ) ),
|
||||
'order' => sanitize_text_field( (string) ( $args['order'] ?? '' ) ),
|
||||
'offset' => $offset,
|
||||
'per_page' => $per_page,
|
||||
];
|
||||
|
||||
/**
|
||||
* Filter to allow overriding the links REST response.
|
||||
*
|
||||
* Return a non-null array to bypass the Free plugin's query entirely.
|
||||
* Expected format: [ 'links' => array, 'total' => int, 'pages' => int ]
|
||||
*
|
||||
* @since 1.0.266
|
||||
*
|
||||
* @param null|array $override Return override data or null to use Free's query.
|
||||
* @param array $normalized Normalized query arguments.
|
||||
*/
|
||||
$override = apply_filters( 'rank_math/links/rest_links_response', null, $normalized );
|
||||
if ( null !== $override ) {
|
||||
return (array) $override;
|
||||
}
|
||||
|
||||
$results = $this->query_links( $normalized );
|
||||
$total = $this->query_links_count( $normalized );
|
||||
|
||||
return [
|
||||
'links' => $results,
|
||||
'total' => (int) $total,
|
||||
'pages' => (int) ceil( $total / $per_page ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get basic links statistics (total, internal, external).
|
||||
*
|
||||
* @return WP_REST_Response
|
||||
*/
|
||||
public function get_links_stats() {
|
||||
/**
|
||||
* Filter to allow overriding the links-stats REST response.
|
||||
*
|
||||
* @since 1.0.266
|
||||
*
|
||||
* @param null|array $override Return override data or null to use Free's query.
|
||||
*/
|
||||
$override = apply_filters( 'rank_math/links/rest_links_stats_response', null );
|
||||
if ( null !== $override ) {
|
||||
return rest_ensure_response( $override );
|
||||
}
|
||||
|
||||
$cache_key = 'links_stats';
|
||||
$cached = wp_cache_get( $cache_key, self::CACHE_GROUP );
|
||||
if ( false !== $cached ) {
|
||||
return rest_ensure_response( $cached );
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'rank_math_internal_links';
|
||||
|
||||
$stats = $wpdb->get_row(
|
||||
"SELECT
|
||||
COUNT(*) as total,
|
||||
SUM(CASE WHEN type = 'internal' THEN 1 ELSE 0 END) as internal,
|
||||
SUM(CASE WHEN type = 'external' THEN 1 ELSE 0 END) as external
|
||||
FROM {$table}"
|
||||
);
|
||||
|
||||
$response = [
|
||||
'total' => (int) ( $stats->total ?? 0 ),
|
||||
'internal' => (int) ( $stats->internal ?? 0 ),
|
||||
'external' => (int) ( $stats->external ?? 0 ),
|
||||
];
|
||||
|
||||
wp_cache_set( $cache_key, $response, self::CACHE_GROUP, self::CACHE_TTL );
|
||||
|
||||
return rest_ensure_response( $response );
|
||||
}
|
||||
|
||||
/**
|
||||
* Query posts with link metrics from Free tables.
|
||||
*
|
||||
* @param array $args Query arguments.
|
||||
* @return array
|
||||
*/
|
||||
private function query_posts( $args ) {
|
||||
$cache_key = 'posts_' . md5( wp_json_encode( $args ) );
|
||||
$cached = wp_cache_get( $cache_key, self::CACHE_GROUP );
|
||||
if ( false !== $cached ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
|
||||
$where_sql = $this->build_posts_where( $args );
|
||||
$orderby = $this->validate_posts_orderby( $args['orderby'] );
|
||||
$order = $this->validate_order( $args['order'], 'ASC' );
|
||||
$limit_sql = $wpdb->prepare( 'LIMIT %d OFFSET %d', $args['per_page'], $args['offset'] );
|
||||
|
||||
$results = $wpdb->get_results(
|
||||
"SELECT p.ID as post_id,
|
||||
p.post_title,
|
||||
p.post_type,
|
||||
p.post_modified,
|
||||
m.internal_link_count,
|
||||
m.external_link_count,
|
||||
m.incoming_link_count,
|
||||
pm_score.meta_value as seo_score
|
||||
FROM {$wpdb->prefix}rank_math_internal_meta m
|
||||
INNER JOIN {$wpdb->posts} p ON m.object_id = p.ID
|
||||
LEFT JOIN {$wpdb->postmeta} pm_score ON p.ID = pm_score.post_id AND pm_score.meta_key = 'rank_math_seo_score'
|
||||
WHERE {$where_sql}
|
||||
ORDER BY {$orderby} {$order}
|
||||
{$limit_sql}"
|
||||
);
|
||||
|
||||
foreach ( $results as $row ) {
|
||||
$row->internal_link_count = (int) ( $row->internal_link_count ?? 0 );
|
||||
$row->external_link_count = (int) ( $row->external_link_count ?? 0 );
|
||||
$row->incoming_link_count = (int) ( $row->incoming_link_count ?? 0 );
|
||||
$row->seo_score = $row->seo_score ? (int) $row->seo_score : 0;
|
||||
$row->is_orphan = 0 === $row->incoming_link_count;
|
||||
$row->edit_url = get_edit_post_link( $row->post_id, '&' );
|
||||
$row->post_url = $this->get_relative_permalink( $row->post_id );
|
||||
$post_type_obj = get_post_type_object( $row->post_type );
|
||||
$row->post_type_label = $post_type_obj ? $post_type_obj->labels->singular_name : ucfirst( $row->post_type );
|
||||
}
|
||||
|
||||
wp_cache_set( $cache_key, $results, self::CACHE_GROUP, self::CACHE_TTL );
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count posts matching query arguments.
|
||||
*
|
||||
* @param array $args Query arguments.
|
||||
* @return int
|
||||
*/
|
||||
private function query_posts_count( $args ) {
|
||||
$cache_key = 'posts_count_' . md5( wp_json_encode( $args ) );
|
||||
$cached = wp_cache_get( $cache_key, self::CACHE_GROUP );
|
||||
if ( false !== $cached ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
|
||||
$where_sql = $this->build_posts_where( $args );
|
||||
$joins = "INNER JOIN {$wpdb->posts} p ON m.object_id = p.ID";
|
||||
|
||||
if ( ! empty( $args['seo_score_range'] ) ) {
|
||||
$joins .= " LEFT JOIN {$wpdb->postmeta} pm_score ON p.ID = pm_score.post_id AND pm_score.meta_key = 'rank_math_seo_score'";
|
||||
}
|
||||
|
||||
$count = (int) $wpdb->get_var(
|
||||
"SELECT COUNT(DISTINCT m.object_id)
|
||||
FROM {$wpdb->prefix}rank_math_internal_meta m
|
||||
{$joins}
|
||||
WHERE {$where_sql}"
|
||||
);
|
||||
|
||||
wp_cache_set( $cache_key, $count, self::CACHE_GROUP, self::CACHE_TTL );
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query links from Free tables.
|
||||
*
|
||||
* @param array $args Query arguments.
|
||||
* @return array
|
||||
*/
|
||||
private function query_links( $args ) {
|
||||
$cache_key = 'links_' . md5( wp_json_encode( $args ) );
|
||||
$cached = wp_cache_get( $cache_key, self::CACHE_GROUP );
|
||||
if ( false !== $cached ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
|
||||
$where_sql = $this->build_links_where( $args );
|
||||
$orderby = $this->validate_links_orderby( $args['orderby'] );
|
||||
$order = $this->validate_order( $args['order'], 'DESC' );
|
||||
$limit_sql = $wpdb->prepare( 'LIMIT %d OFFSET %d', $args['per_page'], $args['offset'] );
|
||||
$table = $wpdb->prefix . 'rank_math_internal_links';
|
||||
|
||||
$results = $wpdb->get_results(
|
||||
"SELECT l.id, l.url, l.post_id, l.target_post_id, l.type,
|
||||
sp.post_title as source_title,
|
||||
tp.post_title as target_title
|
||||
FROM {$table} l
|
||||
LEFT JOIN {$wpdb->posts} sp ON l.post_id = sp.ID
|
||||
LEFT JOIN {$wpdb->posts} tp ON l.target_post_id = tp.ID
|
||||
WHERE {$where_sql}
|
||||
ORDER BY {$orderby} {$order}
|
||||
{$limit_sql}"
|
||||
);
|
||||
|
||||
foreach ( $results as $row ) {
|
||||
$row->source_url = $this->get_relative_permalink( $row->post_id );
|
||||
$row->source_edit_url = $row->post_id ? get_edit_post_link( $row->post_id, '&' ) : '';
|
||||
$row->target_url = ( 'internal' === $row->type ) ? $this->get_relative_permalink( $row->target_post_id ) : '';
|
||||
}
|
||||
|
||||
wp_cache_set( $cache_key, $results, self::CACHE_GROUP, self::CACHE_TTL );
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count links matching query arguments.
|
||||
*
|
||||
* @param array $args Query arguments.
|
||||
* @return int
|
||||
*/
|
||||
private function query_links_count( $args ) {
|
||||
$cache_key = 'links_count_' . md5( wp_json_encode( $args ) );
|
||||
$cached = wp_cache_get( $cache_key, self::CACHE_GROUP );
|
||||
if ( false !== $cached ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'rank_math_internal_links';
|
||||
$where_sql = $this->build_links_where( $args );
|
||||
|
||||
$count = (int) $wpdb->get_var(
|
||||
"SELECT COUNT(*) FROM {$table} l WHERE {$where_sql}"
|
||||
);
|
||||
|
||||
wp_cache_set( $cache_key, $count, self::CACHE_GROUP, self::CACHE_TTL );
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build WHERE clause for posts query.
|
||||
*
|
||||
* @param array $args Query arguments.
|
||||
* @return string
|
||||
*/
|
||||
private function build_posts_where( $args ) {
|
||||
global $wpdb;
|
||||
|
||||
$where = [ "p.post_status = 'publish'" ];
|
||||
|
||||
// Post type filter.
|
||||
$post_types = array_filter( array_map( 'sanitize_text_field', (array) $args['post_type'] ) );
|
||||
if ( ! empty( $post_types ) ) {
|
||||
$placeholders = implode( ', ', array_fill( 0, count( $post_types ), '%s' ) );
|
||||
// phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
|
||||
$where[] = $wpdb->prepare( 'p.post_type IN (' . $placeholders . ')', ...$post_types );
|
||||
} else {
|
||||
$where[] = "p.post_type IN ('post', 'page')";
|
||||
}
|
||||
|
||||
// Orphan filter.
|
||||
if ( isset( $args['is_orphan'] ) && '' !== $args['is_orphan'] ) {
|
||||
if ( 'orphan' === $args['is_orphan'] ) {
|
||||
$where[] = '(m.incoming_link_count IS NULL OR m.incoming_link_count = 0)';
|
||||
} elseif ( 'linked' === $args['is_orphan'] ) {
|
||||
$where[] = 'm.incoming_link_count > 0';
|
||||
}
|
||||
}
|
||||
|
||||
// SEO score range filter.
|
||||
if ( ! empty( $args['seo_score_range'] ) ) {
|
||||
switch ( $args['seo_score_range'] ) {
|
||||
case 'great':
|
||||
$where[] = 'CAST(pm_score.meta_value AS UNSIGNED) > 80';
|
||||
break;
|
||||
case 'good':
|
||||
$where[] = 'CAST(pm_score.meta_value AS UNSIGNED) BETWEEN 51 AND 80';
|
||||
break;
|
||||
case 'bad':
|
||||
$where[] = 'CAST(pm_score.meta_value AS UNSIGNED) <= 50';
|
||||
break;
|
||||
case 'no-score':
|
||||
$where[] = "(pm_score.meta_value IS NULL OR pm_score.meta_value = '')";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Post ID filter.
|
||||
if ( ! empty( $args['post_id'] ) ) {
|
||||
$where[] = $wpdb->prepare( 'p.ID = %d', $args['post_id'] );
|
||||
}
|
||||
|
||||
// Search filter.
|
||||
if ( ! empty( $args['search'] ) ) {
|
||||
$where[] = $wpdb->prepare(
|
||||
'p.post_title LIKE %s',
|
||||
'%' . $wpdb->esc_like( $args['search'] ) . '%'
|
||||
);
|
||||
}
|
||||
|
||||
return implode( ' AND ', $where );
|
||||
}
|
||||
|
||||
/**
|
||||
* Build WHERE clause for links query.
|
||||
*
|
||||
* @param array $args Query arguments.
|
||||
* @return string
|
||||
*/
|
||||
private function build_links_where( $args ) {
|
||||
global $wpdb;
|
||||
|
||||
$where = [ '1=1' ];
|
||||
|
||||
if ( ! empty( $args['source_id'] ) ) {
|
||||
$where[] = $wpdb->prepare( 'l.post_id = %d', $args['source_id'] );
|
||||
}
|
||||
|
||||
if ( ! empty( $args['target_post_id'] ) ) {
|
||||
$where[] = $wpdb->prepare( 'l.target_post_id = %d', $args['target_post_id'] );
|
||||
}
|
||||
|
||||
if ( isset( $args['is_internal'] ) && '' !== $args['is_internal'] ) {
|
||||
$type = '1' === $args['is_internal'] ? 'internal' : 'external';
|
||||
$where[] = $wpdb->prepare( 'l.type = %s', $type );
|
||||
}
|
||||
|
||||
if ( ! empty( $args['search'] ) ) {
|
||||
$where[] = $wpdb->prepare(
|
||||
'l.url LIKE %s',
|
||||
'%' . $wpdb->esc_like( $args['search'] ) . '%'
|
||||
);
|
||||
}
|
||||
|
||||
return implode( ' AND ', $where );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate ORDER direction.
|
||||
*
|
||||
* @param string $order Input order.
|
||||
* @param string $default_order Default order.
|
||||
* @return string
|
||||
*/
|
||||
private function validate_order( $order, $default_order = 'DESC' ) {
|
||||
$order = strtoupper( $order );
|
||||
return in_array( $order, [ 'ASC', 'DESC' ], true ) ? $order : $default_order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and return ORDER BY column for posts query.
|
||||
*
|
||||
* @param string $orderby Input orderby.
|
||||
* @return string
|
||||
*/
|
||||
private function validate_posts_orderby( $orderby ) {
|
||||
$map = [
|
||||
'post_title' => 'p.post_title',
|
||||
'internal_link_count' => 'm.internal_link_count',
|
||||
'external_link_count' => 'm.external_link_count',
|
||||
'incoming_link_count' => 'm.incoming_link_count',
|
||||
'seo_score' => 'pm_score.meta_value',
|
||||
'post_modified' => 'p.post_modified',
|
||||
];
|
||||
return isset( $map[ $orderby ] ) ? $map[ $orderby ] : 'p.post_title';
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and return ORDER BY column for links query.
|
||||
*
|
||||
* @param string $orderby Input orderby.
|
||||
* @return string
|
||||
*/
|
||||
private function validate_links_orderby( $orderby ) {
|
||||
$map = [
|
||||
'id' => 'l.id',
|
||||
'url' => 'l.url',
|
||||
'type' => 'l.type',
|
||||
'source_title' => 'sp.post_title',
|
||||
];
|
||||
return isset( $map[ $orderby ] ) ? $map[ $orderby ] : 'l.id';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get relative permalink (without home_url prefix).
|
||||
*
|
||||
* @param int $post_id Post ID.
|
||||
* @return string
|
||||
*/
|
||||
private function get_relative_permalink( $post_id ) {
|
||||
if ( empty( $post_id ) ) {
|
||||
return '';
|
||||
}
|
||||
$permalink = get_permalink( $post_id );
|
||||
if ( ! $permalink ) {
|
||||
return '';
|
||||
}
|
||||
return str_replace( untrailingslashit( home_url() ), '', $permalink );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get argument definitions for the /posts endpoint.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_posts_args() {
|
||||
return [
|
||||
'page' => [
|
||||
'description' => esc_html__( 'Page number.', 'seo-by-rank-math' ),
|
||||
'type' => 'integer',
|
||||
'default' => 1,
|
||||
],
|
||||
'per_page' => [
|
||||
'description' => esc_html__( 'Items per page.', 'seo-by-rank-math' ),
|
||||
'type' => 'integer',
|
||||
'default' => 50,
|
||||
'maximum' => 100,
|
||||
],
|
||||
'search' => [
|
||||
'description' => esc_html__( 'Search in post title.', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'default' => '',
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'post_type' => [
|
||||
'description' => esc_html__( 'Filter by post type. Supports multiple values.', 'seo-by-rank-math' ),
|
||||
'type' => 'array',
|
||||
'items' => [ 'type' => 'string' ],
|
||||
'default' => [],
|
||||
'sanitize_callback' => function ( $param ) {
|
||||
return array_map( 'sanitize_text_field', (array) $param );
|
||||
},
|
||||
],
|
||||
'is_orphan' => [
|
||||
'description' => esc_html__( 'Filter by orphan status (orphan, linked).', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'default' => '',
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'seo_score_range' => [
|
||||
'description' => esc_html__( 'Filter by SEO score range (great, good, bad, no-score).', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'default' => '',
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'post_id' => [
|
||||
'description' => esc_html__( 'Filter by post ID.', 'seo-by-rank-math' ),
|
||||
'type' => 'integer',
|
||||
'default' => 0,
|
||||
'sanitize_callback' => 'absint',
|
||||
],
|
||||
'orderby' => [
|
||||
'description' => esc_html__( 'Order by field.', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'default' => 'post_title',
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'order' => [
|
||||
'description' => esc_html__( 'Order direction (ASC, DESC).', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'default' => 'ASC',
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get argument definitions for the /links endpoint.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_links_args() {
|
||||
return [
|
||||
'page' => [
|
||||
'description' => esc_html__( 'Page number.', 'seo-by-rank-math' ),
|
||||
'type' => 'integer',
|
||||
'default' => 1,
|
||||
],
|
||||
'per_page' => [
|
||||
'description' => esc_html__( 'Items per page.', 'seo-by-rank-math' ),
|
||||
'type' => 'integer',
|
||||
'default' => 50,
|
||||
'maximum' => 100,
|
||||
],
|
||||
'search' => [
|
||||
'description' => esc_html__( 'Search in URL.', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'default' => '',
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'source_id' => [
|
||||
'description' => esc_html__( 'Filter by source post ID.', 'seo-by-rank-math' ),
|
||||
'type' => 'integer',
|
||||
'default' => 0,
|
||||
],
|
||||
'target_post_id' => [
|
||||
'description' => esc_html__( 'Filter by target post ID.', 'seo-by-rank-math' ),
|
||||
'type' => 'integer',
|
||||
'default' => 0,
|
||||
],
|
||||
'is_internal' => [
|
||||
'description' => esc_html__( 'Filter by link type (1 = internal, 0 = external).', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'default' => '',
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'orderby' => [
|
||||
'description' => esc_html__( 'Order by field.', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'default' => 'id',
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
'order' => [
|
||||
'description' => esc_html__( 'Order direction (ASC, DESC).', 'seo-by-rank-math' ),
|
||||
'type' => 'string',
|
||||
'default' => 'DESC',
|
||||
'sanitize_callback' => 'sanitize_text_field',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
File diff suppressed because one or more lines are too long
+112
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* LinksPage component.
|
||||
*
|
||||
* Main Links admin page with Posts and Links tabs.
|
||||
* Uses DashboardHeader and TabPanel from @rank-math/components.
|
||||
*/
|
||||
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n'
|
||||
import { useState, useEffect, createElement } from '@wordpress/element'
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Posts from './tabs/Posts'
|
||||
import Links from './tabs/Links'
|
||||
import BulkUpdate from './tabs/BulkUpdate'
|
||||
import KeywordMaps from './tabs/KeywordMaps'
|
||||
import { DashboardHeader, TabPanel } from '@rank-math/components'
|
||||
|
||||
/**
|
||||
* Parse URL hash to get active tab name.
|
||||
*
|
||||
* @param {string} hash URL hash string.
|
||||
* @return {string} Active tab name ('posts' or 'links').
|
||||
*/
|
||||
const getTabFromHash = ( hash ) => {
|
||||
if ( ! hash || hash === '#' ) {
|
||||
return 'posts'
|
||||
}
|
||||
const tabName = hash.replace( '#', '' ).split( '?' )[ 0 ]
|
||||
return tabName
|
||||
}
|
||||
|
||||
const getTabs = () => [
|
||||
{
|
||||
id: 'posts',
|
||||
name: 'posts',
|
||||
title: __( 'Posts', 'seo-by-rank-math' ),
|
||||
view: Posts,
|
||||
className: 'rank-math-posts-tab rank-math-tab',
|
||||
},
|
||||
{
|
||||
id: 'links',
|
||||
name: 'links',
|
||||
title: __( 'Links', 'seo-by-rank-math' ),
|
||||
view: Links,
|
||||
className: 'rank-math-links-tab rank-math-tab',
|
||||
},
|
||||
{
|
||||
id: 'bulk-update',
|
||||
name: 'bulk-update',
|
||||
title: __( 'Bulk Update', 'seo-by-rank-math' ),
|
||||
view: BulkUpdate,
|
||||
className: 'rank-math-bulk-update-tab rank-math-tab',
|
||||
},
|
||||
{
|
||||
id: 'keyword-maps',
|
||||
name: 'keyword-maps',
|
||||
title: __( 'Keyword Maps', 'seo-by-rank-math' ),
|
||||
view: KeywordMaps,
|
||||
className: 'rank-math-keyword-maps-tab rank-math-tab',
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* Main Links page component.
|
||||
*/
|
||||
const LinksPage = () => {
|
||||
const [ currentHash, setCurrentHash ] = useState( window.location.hash )
|
||||
|
||||
useEffect( () => {
|
||||
const handleHashChange = () => {
|
||||
setCurrentHash( window.location.hash )
|
||||
}
|
||||
window.addEventListener( 'hashchange', handleHashChange )
|
||||
return () => window.removeEventListener( 'hashchange', handleHashChange )
|
||||
}, [] )
|
||||
|
||||
const activeTab = getTabFromHash( currentHash )
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardHeader page={ __( 'AI Link Genius', 'seo-by-rank-math' ) } />
|
||||
<div className="wrap rank-math-wrap rank-math-links-page">
|
||||
<TabPanel
|
||||
key={ activeTab }
|
||||
className="rank-math-tabs"
|
||||
activeClass="is-active"
|
||||
initialTabName={ activeTab }
|
||||
tabs={ getTabs() }
|
||||
onSelect={ ( tabName ) => {
|
||||
const currentTabName = getTabFromHash( window.location.hash )
|
||||
if ( currentTabName !== tabName ) {
|
||||
window.location.hash = tabName
|
||||
}
|
||||
} }
|
||||
>
|
||||
{ ( tab ) => (
|
||||
<div className={ 'rank-math-tab-content rank-math-tab-content-' + tab.name }>
|
||||
{ createElement( tab.view, { key: tab.name } ) }
|
||||
</div>
|
||||
) }
|
||||
</TabPanel>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default LinksPage
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* useTableData hook.
|
||||
*
|
||||
* Fetches paginated, filterable table data from a REST endpoint.
|
||||
*/
|
||||
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { useState, useEffect, useCallback, useRef } from '@wordpress/element'
|
||||
import apiFetch from '@wordpress/api-fetch'
|
||||
|
||||
/**
|
||||
* Fetch data from a REST endpoint with query args.
|
||||
*
|
||||
* @param {string} endpoint REST endpoint path (e.g. '/rankmath/v1/links/posts').
|
||||
* @param {Object} params Query parameters.
|
||||
* @return {Promise<Object>} Response data.
|
||||
*/
|
||||
const fetchData = ( endpoint, params ) => {
|
||||
const query = Object.entries( params )
|
||||
.filter( ( [ , v ] ) => v !== '' && v !== null && v !== undefined )
|
||||
.map( ( [ k, v ] ) => {
|
||||
if ( Array.isArray( v ) ) {
|
||||
return v.map( ( item ) => `${ encodeURIComponent( k ) }[]=${ encodeURIComponent( item ) }` ).join( '&' )
|
||||
}
|
||||
return `${ encodeURIComponent( k ) }=${ encodeURIComponent( v ) }`
|
||||
} )
|
||||
.join( '&' )
|
||||
|
||||
return apiFetch( { path: `${ endpoint }?${ query }` } )
|
||||
}
|
||||
|
||||
/**
|
||||
* useTableData hook.
|
||||
*
|
||||
* @param {Object} options Hook options.
|
||||
* @param {string} options.dataEndpoint REST endpoint for rows.
|
||||
* @param {string} options.statsEndpoint REST endpoint for stats.
|
||||
* @param {Object} options.initialFilters Initial filter values.
|
||||
* @return {Object} Table state and handlers.
|
||||
*/
|
||||
const useTableData = ( { dataEndpoint, statsEndpoint, initialFilters = {} } ) => {
|
||||
const [ data, setData ] = useState( [] )
|
||||
const [ stats, setStats ] = useState( null )
|
||||
const [ loading, setLoading ] = useState( true )
|
||||
const [ filters, setFilters ] = useState( initialFilters )
|
||||
const [ sortConfig, setSortConfig ] = useState( {
|
||||
orderby: initialFilters.orderby || '',
|
||||
order: initialFilters.order || 'ASC',
|
||||
} )
|
||||
const [ pagination, setPagination ] = useState( {
|
||||
page: 1,
|
||||
perPage: 10,
|
||||
total: 0,
|
||||
pages: 0,
|
||||
} )
|
||||
|
||||
const fetchingRef = useRef( false )
|
||||
const isMountedRef = useRef( true )
|
||||
|
||||
useEffect( () => {
|
||||
isMountedRef.current = true
|
||||
return () => {
|
||||
isMountedRef.current = false
|
||||
}
|
||||
}, [] )
|
||||
|
||||
const fetchAll = useCallback( async ( currentFilters, currentSort, currentPage, perPage ) => {
|
||||
if ( fetchingRef.current ) {
|
||||
return
|
||||
}
|
||||
fetchingRef.current = true
|
||||
setLoading( true )
|
||||
|
||||
const params = {
|
||||
...currentFilters,
|
||||
orderby: currentSort.orderby,
|
||||
order: currentSort.order,
|
||||
page: currentPage,
|
||||
per_page: perPage,
|
||||
}
|
||||
|
||||
try {
|
||||
const [ dataResponse, statsResponse ] = await Promise.all( [
|
||||
fetchData( dataEndpoint, params ),
|
||||
statsEndpoint ? fetchData( statsEndpoint, {} ) : Promise.resolve( null ),
|
||||
] )
|
||||
|
||||
if ( ! isMountedRef.current ) {
|
||||
return
|
||||
}
|
||||
|
||||
// Determine data key from response (posts or links).
|
||||
const dataKey = dataResponse.posts ? 'posts' : 'links'
|
||||
setData( dataResponse[ dataKey ] || [] )
|
||||
setPagination( ( prev ) => ( {
|
||||
...prev,
|
||||
page: currentPage,
|
||||
perPage,
|
||||
total: dataResponse.total || 0,
|
||||
pages: dataResponse.pages || 0,
|
||||
} ) )
|
||||
|
||||
if ( statsResponse ) {
|
||||
setStats( statsResponse )
|
||||
}
|
||||
} catch ( error ) {
|
||||
if ( isMountedRef.current ) {
|
||||
setData( [] )
|
||||
}
|
||||
} finally {
|
||||
if ( isMountedRef.current ) {
|
||||
setLoading( false )
|
||||
}
|
||||
fetchingRef.current = false
|
||||
}
|
||||
}, [ dataEndpoint, statsEndpoint ] ) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Re-fetch when filters, sort, or page changes.
|
||||
useEffect( () => {
|
||||
fetchAll( filters, sortConfig, pagination.page, pagination.perPage )
|
||||
}, [ filters, sortConfig, pagination.page, pagination.perPage ] ) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const handleFilterChange = useCallback( ( key, value ) => {
|
||||
setFilters( ( prev ) => ( { ...prev, [ key ]: value } ) )
|
||||
setPagination( ( prev ) => ( { ...prev, page: 1 } ) )
|
||||
}, [] )
|
||||
|
||||
const handlePageChange = useCallback( ( newPage ) => {
|
||||
setPagination( ( prev ) => ( { ...prev, page: newPage } ) )
|
||||
}, [] )
|
||||
|
||||
const handlePerPageChange = useCallback( ( newPerPage ) => {
|
||||
setPagination( ( prev ) => ( { ...prev, page: 1, perPage: newPerPage } ) )
|
||||
}, [] )
|
||||
|
||||
const handleSortChange = useCallback( ( orderby, order ) => {
|
||||
setSortConfig( { orderby, order } )
|
||||
setPagination( ( prev ) => ( { ...prev, page: 1 } ) )
|
||||
}, [] )
|
||||
|
||||
return {
|
||||
data,
|
||||
stats,
|
||||
loading,
|
||||
pagination,
|
||||
filters,
|
||||
sortConfig,
|
||||
handleFilterChange,
|
||||
handlePageChange,
|
||||
handlePerPageChange,
|
||||
handleSortChange,
|
||||
}
|
||||
}
|
||||
|
||||
export default useTableData
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import ErrorCTA from '@components/ErrorCTA'
|
||||
|
||||
const BulkUpdate = () => {
|
||||
const imagesUrl = window.rankMath.links?.imagesUrl || ''
|
||||
|
||||
return (
|
||||
<div className="rank-math-pro-tab-preview">
|
||||
<img src={ imagesUrl + 'bulk-update.jpg' } alt="" />
|
||||
<ErrorCTA showProNotice={ true } width="width-50" medium="Bulk+Update" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default BulkUpdate
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import ErrorCTA from '@components/ErrorCTA'
|
||||
|
||||
const KeywordMaps = () => {
|
||||
const imagesUrl = window.rankMath.links?.imagesUrl || ''
|
||||
|
||||
return (
|
||||
<div className="rank-math-pro-tab-preview">
|
||||
<img src={ imagesUrl + 'keyword-maps.jpg' } alt="" />
|
||||
<ErrorCTA showProNotice={ true } width="width-50" medium="Keyword+Maps" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KeywordMaps
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
/**
|
||||
* Links tab component.
|
||||
*
|
||||
* Shows links with URL, source post, and type.
|
||||
* PRO-only filters (anchor type, nofollow status) appear in the filter row
|
||||
* but open an upgrade CTA when applied.
|
||||
*/
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { get } from 'lodash'
|
||||
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n'
|
||||
import { useState, useCallback, useMemo } from '@wordpress/element'
|
||||
import { Modal } from '@wordpress/components'
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import useTableData from '../hooks/useTableData'
|
||||
import { parseHashParams, URL_PARAMS, setLinkTypeInHash } from '../urlState'
|
||||
import ErrorCTA from '@components/ErrorCTA'
|
||||
|
||||
const { ListTable, TableSkeleton } = window.rankMathComponents
|
||||
|
||||
/**
|
||||
* PRO upgrade modal.
|
||||
*
|
||||
* @param {Function} onClose Callback to close the modal.
|
||||
*/
|
||||
const ProCTAModal = ( { onClose } ) => (
|
||||
<Modal
|
||||
onRequestClose={ onClose }
|
||||
className="rank-math-contentai-modal rank-math-modal rank-math-error-modal"
|
||||
shouldCloseOnClickOutside={ true }
|
||||
>
|
||||
<ErrorCTA showProNotice={ true } medium="Links" />
|
||||
</Modal>
|
||||
)
|
||||
|
||||
/**
|
||||
* Read link filters from the URL hash (set when navigating from Posts tab counts).
|
||||
*
|
||||
* @return {Object} Initial filter values from URL.
|
||||
*/
|
||||
const getLinksFiltersFromURL = () => {
|
||||
const { searchParams } = parseHashParams()
|
||||
const linkType = searchParams.get( URL_PARAMS.LINK_TYPE ) || ''
|
||||
let isInternal = ''
|
||||
if ( linkType === 'internal' ) {
|
||||
isInternal = '1'
|
||||
} else if ( linkType === 'external' ) {
|
||||
isInternal = '0'
|
||||
}
|
||||
return {
|
||||
source_id: parseInt( searchParams.get( URL_PARAMS.SOURCE_ID ), 10 ) || 0,
|
||||
target_post_id: parseInt( searchParams.get( URL_PARAMS.TARGET_POST_ID ), 10 ) || 0,
|
||||
is_internal: isInternal,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Link type badge.
|
||||
*
|
||||
* @param {string} type 'internal' or 'external'
|
||||
*/
|
||||
const LinkTypeBadge = ( { type } ) => (
|
||||
<span className={ `rank-math-link-type-badge ${ type }` }>
|
||||
{ type === 'internal' ? __( 'Internal', 'seo-by-rank-math' ) : __( 'External', 'seo-by-rank-math' ) }
|
||||
</span>
|
||||
)
|
||||
|
||||
/**
|
||||
* Links tab.
|
||||
*
|
||||
* @return {JSX.Element} Links tab content.
|
||||
*/
|
||||
const Links = () => {
|
||||
const [ upgradeModalOpen, setUpgradeModalOpen ] = useState( false )
|
||||
|
||||
// Read initial filters from URL hash (set when clicking counts in Posts tab)
|
||||
const urlFilters = getLinksFiltersFromURL()
|
||||
|
||||
const {
|
||||
data: links,
|
||||
stats,
|
||||
loading,
|
||||
pagination,
|
||||
filters,
|
||||
sortConfig,
|
||||
handleFilterChange,
|
||||
handlePageChange,
|
||||
handlePerPageChange,
|
||||
handleSortChange,
|
||||
} = useTableData( {
|
||||
dataEndpoint: '/rankmath/v1/links/links',
|
||||
statsEndpoint: '/rankmath/v1/links/links-stats',
|
||||
initialFilters: {
|
||||
search: '',
|
||||
source_id: urlFilters.source_id,
|
||||
target_post_id: urlFilters.target_post_id,
|
||||
is_internal: urlFilters.is_internal,
|
||||
orderby: 'id',
|
||||
order: 'DESC',
|
||||
},
|
||||
} )
|
||||
|
||||
// Table headers
|
||||
const headers = useMemo( () => [
|
||||
{
|
||||
key: 'source_title',
|
||||
label: __( 'Source Post', 'seo-by-rank-math' ),
|
||||
isSortable: true,
|
||||
isHideable: false,
|
||||
render: ( value, row ) => (
|
||||
<>
|
||||
{ row.source_edit_url ? (
|
||||
<a href={ row.source_edit_url } target="_blank" rel="noopener noreferrer">
|
||||
{ value || __( '(no title)', 'seo-by-rank-math' ) }
|
||||
</a>
|
||||
) : (
|
||||
value || __( '(no title)', 'seo-by-rank-math' )
|
||||
) }
|
||||
{ row.source_url && (
|
||||
<div className="rank-math-post-url">{ row.source_url }</div>
|
||||
) }
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'url',
|
||||
label: __( 'Destination', 'seo-by-rank-math' ),
|
||||
isSortable: true,
|
||||
isHideable: false,
|
||||
render: ( value, row ) => (
|
||||
<>
|
||||
<a href={ value } target="_blank" rel="noopener noreferrer">
|
||||
{ row.target_title || value }
|
||||
</a>
|
||||
{ row.target_title && (
|
||||
<div className="rank-math-post-url">{ value }</div>
|
||||
) }
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'type',
|
||||
label: __( 'Link Type', 'seo-by-rank-math' ),
|
||||
isSortable: true,
|
||||
render: ( value ) => <LinkTypeBadge type={ value } />,
|
||||
},
|
||||
], [] )
|
||||
|
||||
// Link type toggle options
|
||||
const linkTypeOptions = [
|
||||
{ label: __( 'All', 'seo-by-rank-math' ), value: '' },
|
||||
{ label: __( 'Internal', 'seo-by-rank-math' ), value: '1', statusType: 'internal' },
|
||||
{ label: __( 'External', 'seo-by-rank-math' ), value: '0', statusType: 'external' },
|
||||
]
|
||||
|
||||
// Link status toggle options (PRO-only — clicking any non-All value opens upgrade modal)
|
||||
const linkStatusOptions = [
|
||||
{ label: __( 'All', 'seo-by-rank-math' ), value: '', statusType: 'all' },
|
||||
{ label: __( 'Success', 'seo-by-rank-math' ), value: '2xx', statusType: 'success' },
|
||||
{ label: __( 'Broken', 'seo-by-rank-math' ), value: 'broken', statusType: 'error' },
|
||||
{ label: __( 'Redirects', 'seo-by-rank-math' ), value: '3xx', statusType: 'warning' },
|
||||
{ label: __( 'Robots Blocked', 'seo-by-rank-math' ), value: 'robots_blocked', statusType: 'blocked' },
|
||||
{ label: __( 'Marked Safe', 'seo-by-rank-math' ), value: 'marked_safe', statusType: 'markedSafe' },
|
||||
{ label: __( 'Unchecked', 'seo-by-rank-math' ), value: 'unchecked', statusType: 'unchecked' },
|
||||
]
|
||||
|
||||
const handleStatusToggle = useCallback( ( value ) => {
|
||||
if ( value !== '' ) {
|
||||
setUpgradeModalOpen( true )
|
||||
}
|
||||
}, [ setUpgradeModalOpen ] )
|
||||
|
||||
const handleSortChange2 = useCallback( ( key ) => {
|
||||
const newOrder = sortConfig.orderby === key && sortConfig.order === 'ASC' ? 'DESC' : 'ASC'
|
||||
handleSortChange( key, newOrder )
|
||||
}, [ sortConfig, handleSortChange ] )
|
||||
|
||||
// Footer stats
|
||||
const footerStats = useMemo( () => {
|
||||
if ( ! stats ) {
|
||||
return []
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
label: __( 'Total Links', 'seo-by-rank-math' ),
|
||||
value: get( stats, 'total', 0 ),
|
||||
},
|
||||
{
|
||||
label: __( 'Internal Links', 'seo-by-rank-math' ),
|
||||
value: get( stats, 'internal', 0 ),
|
||||
},
|
||||
{
|
||||
label: __( 'External Links', 'seo-by-rank-math' ),
|
||||
value: get( stats, 'external', 0 ),
|
||||
},
|
||||
]
|
||||
}, [ stats ] )
|
||||
|
||||
// Controlled sort config
|
||||
const tableSortConfig = useMemo( () => ( {
|
||||
key: sortConfig.orderby,
|
||||
direction: sortConfig.order === 'ASC' ? 'asc' : 'desc',
|
||||
} ), [ sortConfig ] )
|
||||
|
||||
if ( loading && links.length === 0 ) {
|
||||
return <TableSkeleton columns={ 3 } rows={ 10 } />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rank-math-section-card">
|
||||
{ upgradeModalOpen && (
|
||||
<ProCTAModal onClose={ () => setUpgradeModalOpen( false ) } />
|
||||
) }
|
||||
<ListTable
|
||||
headers={ headers }
|
||||
rows={ links }
|
||||
stats={ footerStats }
|
||||
// Server-side pagination
|
||||
currentPage={ pagination.page }
|
||||
rowsPerPage={ pagination.perPage }
|
||||
totalItems={ pagination.total }
|
||||
totalPages={ pagination.pages }
|
||||
onPageChange={ handlePageChange }
|
||||
onRowsPerPageChange={ handlePerPageChange }
|
||||
// Server-side sorting
|
||||
sortConfig={ tableSortConfig }
|
||||
onSortChange={ handleSortChange2 }
|
||||
// Server-side filtering
|
||||
activeFilters={ filters }
|
||||
onFilterChange={ ( newFilters ) => {
|
||||
Object.entries( newFilters ).forEach( ( [ key, value ] ) => {
|
||||
handleFilterChange( key, value )
|
||||
} )
|
||||
} }
|
||||
// Link type toggle (tab style)
|
||||
primaryToggle={ {
|
||||
options: linkTypeOptions,
|
||||
value: filters.is_internal !== undefined && filters.is_internal !== '' ? String( filters.is_internal ) : '',
|
||||
filterKey: 'is_internal',
|
||||
onChange: ( value ) => {
|
||||
handleFilterChange( 'is_internal', value )
|
||||
setLinkTypeInHash( value )
|
||||
},
|
||||
} }
|
||||
// Link status toggle (colored pills — PRO-only, opens upgrade modal)
|
||||
secondaryToggle={ {
|
||||
options: linkStatusOptions,
|
||||
value: '',
|
||||
onChange: handleStatusToggle,
|
||||
} }
|
||||
storageKey="links-links"
|
||||
/>
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Links
|
||||
+364
@@ -0,0 +1,364 @@
|
||||
/**
|
||||
* Posts tab component.
|
||||
*
|
||||
* Shows posts with their internal/external/incoming link counts and SEO score.
|
||||
* Uses the shared ListTable component from @rank-math/components.
|
||||
*/
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { entries, map, reject } from 'lodash'
|
||||
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n'
|
||||
import { useState, useCallback, useMemo } from '@wordpress/element'
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import useTableData from '../hooks/useTableData'
|
||||
import {
|
||||
parseHashParams,
|
||||
getPostsFiltersFromURL,
|
||||
setPostsFiltersInHash,
|
||||
clearPostsFiltersFromHash,
|
||||
navigateToLinksTab,
|
||||
} from '../urlState'
|
||||
|
||||
const { ListTable, TableSkeleton } = window.rankMathComponents
|
||||
|
||||
/**
|
||||
* Get available post type options from localized data.
|
||||
*
|
||||
* @return {Array} Array of {label, value} options.
|
||||
*/
|
||||
const getPostTypeOptions = () => {
|
||||
const postTypes = map(
|
||||
entries( window.rankMath.links?.postTypes ),
|
||||
( [ value, label ] ) => ( { value, label } )
|
||||
)
|
||||
return reject( postTypes, { value: 'attachment' } )
|
||||
}
|
||||
|
||||
/**
|
||||
* Render SEO score badge.
|
||||
*
|
||||
* @param {number} score SEO score value (0-100).
|
||||
*/
|
||||
const SeoScoreBadge = ( { score } ) => {
|
||||
if ( ! score ) {
|
||||
return (
|
||||
<span className="rank-math-seo-score na">
|
||||
<strong>{ __( 'Not Set', 'seo-by-rank-math' ) }</strong>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
let scoreClass = 'bad'
|
||||
if ( score > 80 ) {
|
||||
scoreClass = 'great'
|
||||
} else if ( score > 50 ) {
|
||||
scoreClass = 'good'
|
||||
}
|
||||
return (
|
||||
<span className={ `rank-math-seo-score ${ scoreClass }` }>
|
||||
<strong>{ score } / 100</strong>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts tab.
|
||||
*
|
||||
* @return {JSX.Element} Posts tab content.
|
||||
*/
|
||||
const Posts = () => {
|
||||
// Read initial filters from URL hash
|
||||
const { tabName, searchParams } = parseHashParams()
|
||||
const urlFilters = getPostsFiltersFromURL( searchParams )
|
||||
|
||||
const [ appliedFilters, setAppliedFilters ] = useState( () => ( {
|
||||
post_type: urlFilters.post_type || [],
|
||||
is_orphan: urlFilters.is_orphan || '',
|
||||
seo_score_range: urlFilters.seo_score_range || '',
|
||||
} ) )
|
||||
|
||||
const {
|
||||
data: posts,
|
||||
stats,
|
||||
loading,
|
||||
pagination,
|
||||
filters,
|
||||
sortConfig,
|
||||
handleFilterChange,
|
||||
handlePageChange,
|
||||
handlePerPageChange,
|
||||
handleSortChange,
|
||||
} = useTableData( {
|
||||
dataEndpoint: '/rankmath/v1/links/posts',
|
||||
statsEndpoint: '/rankmath/v1/links/posts-stats',
|
||||
initialFilters: {
|
||||
search: '',
|
||||
post_type: urlFilters.post_type || [],
|
||||
is_orphan: urlFilters.is_orphan || '',
|
||||
seo_score_range: urlFilters.seo_score_range || '',
|
||||
orderby: 'post_title',
|
||||
order: 'ASC',
|
||||
},
|
||||
} )
|
||||
|
||||
// Navigate to Links tab filtered by this post's links
|
||||
const handleNavigateToLinks = useCallback( ( postId, linkType ) => {
|
||||
const linkFilters = {}
|
||||
if ( linkType === 'incoming' ) {
|
||||
linkFilters.target_post_id = postId
|
||||
} else {
|
||||
linkFilters.source_id = postId
|
||||
if ( linkType === 'internal' ) {
|
||||
linkFilters.link_type = 'internal'
|
||||
} else if ( linkType === 'external' ) {
|
||||
linkFilters.link_type = 'external'
|
||||
}
|
||||
}
|
||||
navigateToLinksTab( linkFilters )
|
||||
}, [] )
|
||||
|
||||
// Table headers definition
|
||||
const headers = useMemo( () => [
|
||||
{
|
||||
key: 'post_title',
|
||||
label: __( 'Post Title', 'seo-by-rank-math' ),
|
||||
isSortable: true,
|
||||
isHideable: false,
|
||||
render: ( value, row ) => (
|
||||
<>
|
||||
{ row.edit_url ? (
|
||||
<a href={ row.edit_url } target="_blank" rel="noopener noreferrer">
|
||||
{ value || __( '(no title)', 'seo-by-rank-math' ) }
|
||||
</a>
|
||||
) : (
|
||||
value || __( '(no title)', 'seo-by-rank-math' )
|
||||
) }
|
||||
{ row.post_url && (
|
||||
<div className="rank-math-post-url">{ row.post_url }</div>
|
||||
) }
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'internal_link_count',
|
||||
label: __( 'Internal Links', 'seo-by-rank-math' ),
|
||||
isSortable: true,
|
||||
render: ( value, row ) => {
|
||||
const count = parseInt( value, 10 ) || 0
|
||||
if ( count === 0 ) {
|
||||
return <span className="rank-math-count-badge">{ count }</span>
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="rank-math-count-badge rank-math-count-badge-link rank-math-tooltip"
|
||||
onClick={ () => handleNavigateToLinks( row.post_id, 'internal' ) }
|
||||
>
|
||||
{ count }
|
||||
<span>{ __( 'View internal links from this post', 'seo-by-rank-math' ) }</span>
|
||||
</button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'external_link_count',
|
||||
label: __( 'External Links', 'seo-by-rank-math' ),
|
||||
isSortable: true,
|
||||
render: ( value, row ) => {
|
||||
const count = parseInt( value, 10 ) || 0
|
||||
if ( count === 0 ) {
|
||||
return <span className="rank-math-count-badge">{ count }</span>
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="rank-math-count-badge rank-math-count-badge-link rank-math-tooltip"
|
||||
onClick={ () => handleNavigateToLinks( row.post_id, 'external' ) }
|
||||
>
|
||||
{ count }
|
||||
<span>{ __( 'View external links from this post', 'seo-by-rank-math' ) }</span>
|
||||
</button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'incoming_link_count',
|
||||
label: __( 'Incoming Links', 'seo-by-rank-math' ),
|
||||
isSortable: true,
|
||||
render: ( value, row ) => {
|
||||
const count = parseInt( value, 10 ) || 0
|
||||
if ( count === 0 ) {
|
||||
return (
|
||||
<span className="rank-math-orphan-warning rank-math-tooltip" title={ __( 'Orphan post — no incoming links', 'seo-by-rank-math' ) }>
|
||||
<i className="dashicons dashicons-warning" />
|
||||
<span>{ __( 'This post has no internal links. We recommend that you add links to this URL in other posts of your website.', 'seo-by-rank-math' ) }</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="rank-math-count-badge rank-math-count-badge-link rank-math-tooltip"
|
||||
onClick={ () => handleNavigateToLinks( row.post_id, 'incoming' ) }
|
||||
>
|
||||
{ count }
|
||||
<span>{ __( 'View incoming links to this post', 'seo-by-rank-math' ) }</span>
|
||||
</button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'seo_score',
|
||||
label: __( 'SEO Score', 'seo-by-rank-math' ),
|
||||
isSortable: true,
|
||||
render: ( value ) => <SeoScoreBadge score={ value } />,
|
||||
},
|
||||
{
|
||||
key: 'post_type_label',
|
||||
label: __( 'Type', 'seo-by-rank-math' ),
|
||||
isSortable: false,
|
||||
render: ( value, row ) => value || row.post_type,
|
||||
},
|
||||
], [ handleNavigateToLinks ] )
|
||||
|
||||
// Orphan filter toggle options — statusType drives active/hover color
|
||||
const orphanOptions = [
|
||||
{ label: __( 'All Posts', 'seo-by-rank-math' ), value: '', statusType: 'all' },
|
||||
{ label: __( 'Orphan Posts', 'seo-by-rank-math' ), value: 'orphan', statusType: 'orphan' },
|
||||
{ label: __( 'With Incoming Links', 'seo-by-rank-math' ), value: 'linked', statusType: 'linked' },
|
||||
]
|
||||
|
||||
// SEO score range filter toggle options — statusType drives colored pill colors
|
||||
const seoScoreOptions = [
|
||||
{ label: __( 'All Scores', 'seo-by-rank-math' ), value: '', statusType: 'all' },
|
||||
{ label: __( 'Great', 'seo-by-rank-math' ), value: 'great', statusType: 'great' },
|
||||
{ label: __( 'Good', 'seo-by-rank-math' ), value: 'good', statusType: 'good' },
|
||||
{ label: __( 'Bad', 'seo-by-rank-math' ), value: 'bad', statusType: 'bad' },
|
||||
{ label: __( 'Not Set', 'seo-by-rank-math' ), value: 'no-score', statusType: 'no-score' },
|
||||
]
|
||||
|
||||
// Post type filter via FilterStaging (multi-select)
|
||||
const filterStagingFilters = useMemo( () => [
|
||||
{
|
||||
key: 'post_type',
|
||||
label: __( 'Post Type', 'seo-by-rank-math' ),
|
||||
multiSelect: true,
|
||||
allLabel: __( 'All Types', 'seo-by-rank-math' ),
|
||||
options: getPostTypeOptions(),
|
||||
},
|
||||
], [] )
|
||||
|
||||
const handleSortChange2 = useCallback( ( key ) => {
|
||||
const newOrder = sortConfig.orderby === key && sortConfig.order === 'ASC' ? 'DESC' : 'ASC'
|
||||
handleSortChange( key, newOrder )
|
||||
}, [ sortConfig, handleSortChange ] )
|
||||
|
||||
// Apply staged filters to URL hash and to API
|
||||
const handleApplyFilters = useCallback( ( pendingFilters ) => {
|
||||
setAppliedFilters( pendingFilters )
|
||||
setPostsFiltersInHash( tabName, pendingFilters )
|
||||
if ( pendingFilters.post_type !== undefined ) {
|
||||
handleFilterChange( 'post_type', pendingFilters.post_type )
|
||||
}
|
||||
}, [ tabName, handleFilterChange ] )
|
||||
|
||||
const handleClearFilters = useCallback( ( clearedFilters ) => {
|
||||
setAppliedFilters( clearedFilters )
|
||||
clearPostsFiltersFromHash( tabName )
|
||||
handleFilterChange( 'post_type', [] )
|
||||
}, [ tabName, handleFilterChange ] )
|
||||
|
||||
// Sync toggle filters immediately to URL hash
|
||||
const handleOrphanChange = useCallback( ( value ) => {
|
||||
handleFilterChange( 'is_orphan', value )
|
||||
const newFilters = { ...appliedFilters, is_orphan: value }
|
||||
setAppliedFilters( newFilters )
|
||||
setPostsFiltersInHash( tabName, newFilters )
|
||||
}, [ appliedFilters, tabName, handleFilterChange ] )
|
||||
|
||||
const handleSeoScoreChange = useCallback( ( value ) => {
|
||||
handleFilterChange( 'seo_score_range', value )
|
||||
const newFilters = { ...appliedFilters, seo_score_range: value }
|
||||
setAppliedFilters( newFilters )
|
||||
setPostsFiltersInHash( tabName, newFilters )
|
||||
}, [ appliedFilters, tabName, handleFilterChange ] )
|
||||
|
||||
// Stats for the pagination footer
|
||||
const footerStats = useMemo( () => {
|
||||
if ( ! stats ) {
|
||||
return []
|
||||
}
|
||||
|
||||
return [
|
||||
{ label: __( 'Total Posts', 'seo-by-rank-math' ), value: ( stats.total_posts || 0 ).toLocaleString() },
|
||||
{ label: __( 'Orphan Posts', 'seo-by-rank-math' ), value: ( stats.orphan_posts || 0 ).toLocaleString() },
|
||||
]
|
||||
}, [ stats ] )
|
||||
|
||||
// Controlled sort config for ListTable
|
||||
const tableSortConfig = useMemo( () => ( {
|
||||
key: sortConfig.orderby,
|
||||
direction: sortConfig.order === 'ASC' ? 'asc' : 'desc',
|
||||
} ), [ sortConfig ] )
|
||||
|
||||
if ( loading && posts.length === 0 ) {
|
||||
return <TableSkeleton columns={ 6 } rows={ 10 } />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rank-math-section-card">
|
||||
<ListTable
|
||||
headers={ headers }
|
||||
rows={ posts }
|
||||
exportFilename="rank-math-posts"
|
||||
stats={ footerStats }
|
||||
// Server-side pagination
|
||||
currentPage={ pagination.page }
|
||||
rowsPerPage={ pagination.perPage }
|
||||
totalItems={ pagination.total }
|
||||
totalPages={ pagination.pages }
|
||||
onPageChange={ handlePageChange }
|
||||
onRowsPerPageChange={ handlePerPageChange }
|
||||
// Server-side sorting
|
||||
sortConfig={ tableSortConfig }
|
||||
onSortChange={ handleSortChange2 }
|
||||
// Server-side filtering (search handled by ListTable's debounced search)
|
||||
activeFilters={ filters }
|
||||
onFilterChange={ ( newFilters ) => {
|
||||
Object.entries( newFilters ).forEach( ( [ key, value ] ) => {
|
||||
handleFilterChange( key, value )
|
||||
} )
|
||||
} }
|
||||
// Orphan filter as primaryToggle (tab style)
|
||||
primaryToggle={ {
|
||||
options: orphanOptions,
|
||||
value: filters.is_orphan || '',
|
||||
onChange: handleOrphanChange,
|
||||
} }
|
||||
// SEO score filter as secondaryToggle (colored pills)
|
||||
secondaryToggle={ {
|
||||
options: seoScoreOptions,
|
||||
value: filters.seo_score_range || '',
|
||||
onChange: handleSeoScoreChange,
|
||||
} }
|
||||
// Post type filter via FilterStaging (multi-select dropdown)
|
||||
filters={ filterStagingFilters }
|
||||
appliedFilters={ appliedFilters }
|
||||
onApplyFilters={ handleApplyFilters }
|
||||
onClearFilters={ handleClearFilters }
|
||||
storageKey="links-posts"
|
||||
/>
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Posts
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* URL State Management Utilities
|
||||
*
|
||||
* Handles URL hash parameter synchronization for table state.
|
||||
* Format: #tabname?param=value
|
||||
*/
|
||||
|
||||
export const URL_PARAMS = {
|
||||
POST_TYPE: 'post_type',
|
||||
IS_ORPHAN: 'is_orphan',
|
||||
SEO_SCORE_RANGE: 'seo_score_range',
|
||||
LINK_TYPE: 'link_type',
|
||||
SOURCE_ID: 'source_id',
|
||||
TARGET_POST_ID: 'target_post_id',
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse current hash to get tab name and search params.
|
||||
*
|
||||
* @return {Object} Object with tabName and searchParams.
|
||||
*/
|
||||
export function parseHashParams() {
|
||||
const hash = window.location.hash // eslint-disable-line no-undef
|
||||
|
||||
if ( ! hash || hash === '#' ) {
|
||||
return { tabName: 'posts', searchParams: new URLSearchParams() } // eslint-disable-line no-undef
|
||||
}
|
||||
|
||||
const hashWithoutPrefix = hash.replace( '#', '' )
|
||||
const [ tabName, queryString ] = hashWithoutPrefix.split( '?' )
|
||||
|
||||
return {
|
||||
tabName: tabName || 'posts',
|
||||
searchParams: new URLSearchParams( queryString || '' ), // eslint-disable-line no-undef
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Posts tab filters from URL search params.
|
||||
*
|
||||
* @param {URLSearchParams} searchParams URL search parameters.
|
||||
* @return {Object} Filter object for Posts tab.
|
||||
*/
|
||||
export function getPostsFiltersFromURL( searchParams ) {
|
||||
const postTypeParam = searchParams.get( URL_PARAMS.POST_TYPE ) || ''
|
||||
const postTypes = postTypeParam ? postTypeParam.split( ',' ).filter( Boolean ) : []
|
||||
|
||||
return {
|
||||
post_type: postTypes.length > 0 ? postTypes : [],
|
||||
is_orphan: searchParams.get( URL_PARAMS.IS_ORPHAN ) || '',
|
||||
seo_score_range: searchParams.get( URL_PARAMS.SEO_SCORE_RANGE ) || '',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Posts tab filters in URL hash.
|
||||
*
|
||||
* @param {string} tabName Current tab name.
|
||||
* @param {Object} filters Filter object to serialize.
|
||||
*/
|
||||
export function setPostsFiltersInHash( tabName, filters ) {
|
||||
const { searchParams } = parseHashParams()
|
||||
|
||||
searchParams.delete( URL_PARAMS.POST_TYPE )
|
||||
searchParams.delete( URL_PARAMS.IS_ORPHAN )
|
||||
searchParams.delete( URL_PARAMS.SEO_SCORE_RANGE )
|
||||
|
||||
if ( filters.post_type && filters.post_type.length > 0 ) {
|
||||
searchParams.set( URL_PARAMS.POST_TYPE, filters.post_type.join( ',' ) )
|
||||
}
|
||||
if ( filters.is_orphan ) {
|
||||
searchParams.set( URL_PARAMS.IS_ORPHAN, filters.is_orphan )
|
||||
}
|
||||
if ( filters.seo_score_range ) {
|
||||
searchParams.set( URL_PARAMS.SEO_SCORE_RANGE, filters.seo_score_range )
|
||||
}
|
||||
|
||||
// Reset to page 1 when filters change.
|
||||
searchParams.set( 'page', '1' )
|
||||
|
||||
const queryString = searchParams.toString()
|
||||
window.location.hash = queryString ? `${ tabName }?${ queryString }` : tabName // eslint-disable-line no-undef
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all Posts tab filters from URL hash.
|
||||
*
|
||||
* @param {string} tabName Current tab name.
|
||||
*/
|
||||
export function clearPostsFiltersFromHash( tabName ) {
|
||||
const { searchParams } = parseHashParams()
|
||||
searchParams.delete( URL_PARAMS.POST_TYPE )
|
||||
searchParams.delete( URL_PARAMS.IS_ORPHAN )
|
||||
searchParams.delete( URL_PARAMS.SEO_SCORE_RANGE )
|
||||
|
||||
// Reset to page 1 when filters are cleared.
|
||||
searchParams.set( 'page', '1' )
|
||||
|
||||
const queryString = searchParams.toString()
|
||||
window.location.hash = queryString ? `${ tabName }?${ queryString }` : tabName // eslint-disable-line no-undef
|
||||
}
|
||||
|
||||
/**
|
||||
* Set link_type filter in URL hash for Links tab.
|
||||
*
|
||||
* @param {string} isInternal Filter value: '1' (internal), '0' (external), or '' (all).
|
||||
*/
|
||||
export function setLinkTypeInHash( isInternal ) {
|
||||
const { searchParams } = parseHashParams()
|
||||
|
||||
searchParams.delete( URL_PARAMS.LINK_TYPE )
|
||||
|
||||
if ( isInternal === '1' ) {
|
||||
searchParams.set( URL_PARAMS.LINK_TYPE, 'internal' )
|
||||
} else if ( isInternal === '0' ) {
|
||||
searchParams.set( URL_PARAMS.LINK_TYPE, 'external' )
|
||||
}
|
||||
|
||||
const queryString = searchParams.toString()
|
||||
window.location.hash = queryString ? `links?${ queryString }` : 'links' // eslint-disable-line no-undef
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to Links tab with pre-set source/target filters.
|
||||
*
|
||||
* @param {string} tabName Current tab name ('posts').
|
||||
* @param {Object} linkFilters Object with source_id, target_post_id, link_type.
|
||||
*/
|
||||
export function navigateToLinksTab( linkFilters ) {
|
||||
const searchParams = new URLSearchParams() // eslint-disable-line no-undef
|
||||
|
||||
if ( linkFilters.source_id ) {
|
||||
searchParams.set( URL_PARAMS.SOURCE_ID, linkFilters.source_id )
|
||||
}
|
||||
if ( linkFilters.target_post_id ) {
|
||||
searchParams.set( URL_PARAMS.TARGET_POST_ID, linkFilters.target_post_id )
|
||||
}
|
||||
if ( linkFilters.link_type ) {
|
||||
searchParams.set( URL_PARAMS.LINK_TYPE, linkFilters.link_type )
|
||||
}
|
||||
|
||||
const queryString = searchParams.toString()
|
||||
window.location.hash = queryString ? `links?${ queryString }` : 'links' // eslint-disable-line no-undef
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Links page entry point.
|
||||
*
|
||||
* Mounts the React app on #rank-math-links-page-container.
|
||||
*/
|
||||
|
||||
/**
|
||||
* WordPress dependencies
|
||||
*/
|
||||
import { createElement, createRoot } from '@wordpress/element'
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import LinksPage from './features/links-page/LinksPage'
|
||||
import './scss/links-page.scss'
|
||||
|
||||
const container = document.getElementById( 'rank-math-links-page-container' )
|
||||
if ( container ) {
|
||||
createRoot( container ).render( createElement( LinksPage ) )
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* SCSS Variables
|
||||
*
|
||||
* Design tokens for the Links module (Free)
|
||||
* Aligned with WordPress admin color palette and PRO design system
|
||||
*/
|
||||
|
||||
// ============================================
|
||||
// Colors - Primary
|
||||
// ============================================
|
||||
$color-primary: #2271b1;
|
||||
$color-primary-hover: #135e96;
|
||||
$color-primary-dark: #0a4b78;
|
||||
$color-primary-light: #e0e5f0;
|
||||
$color-primary-lightest: #f0f4f8;
|
||||
|
||||
// ============================================
|
||||
// Colors - Semantic
|
||||
// ============================================
|
||||
$color-success: #4ab147;
|
||||
$color-success-bg: #d4edda;
|
||||
$color-success-text: #155724;
|
||||
$color-success-dark: #2d7a2a;
|
||||
|
||||
$color-danger: #d63638;
|
||||
$color-danger-hover: #b32d2e;
|
||||
$color-danger-bg: #f8d7da;
|
||||
$color-danger-text: #721c24;
|
||||
|
||||
$color-warning: #f0b849;
|
||||
$color-warning-bg: #fff3cd;
|
||||
$color-warning-text: #856404;
|
||||
|
||||
$color-info: #00a0d2;
|
||||
$color-info-bg: #d1ecf1;
|
||||
$color-info-text: #0c5460;
|
||||
|
||||
// ============================================
|
||||
// Colors - Grays & Text
|
||||
// ============================================
|
||||
$color-text-primary: #1e1e1e;
|
||||
$color-text-secondary: #50575e;
|
||||
$color-text-tertiary: #757575;
|
||||
$color-text-muted: #a0a5aa;
|
||||
$color-text-dark: #1d2327;
|
||||
$color-text-light: #646970;
|
||||
|
||||
$color-border: #e0e0e0;
|
||||
$color-border-light: #f0f0f0;
|
||||
$color-border-dark: #dcdcde;
|
||||
$color-border-input: #8c8f94;
|
||||
|
||||
$color-bg-white: #fff;
|
||||
$color-bg-light: #f8f9fa;
|
||||
$color-bg-lighter: #fafafa;
|
||||
$color-bg-hover: #f6f7f7;
|
||||
$color-bg-gray: #f0f0f1;
|
||||
|
||||
// Skeleton loading colors
|
||||
$color-skeleton-base: #f2f3f5;
|
||||
$color-skeleton-highlight: #e9eaed;
|
||||
|
||||
// ============================================
|
||||
// Spacing
|
||||
// ============================================
|
||||
$spacing-xs: 4px;
|
||||
$spacing-sm: 8px;
|
||||
$spacing-md: 12px;
|
||||
$spacing-lg: 16px;
|
||||
$spacing-xl: 20px;
|
||||
$spacing-2xl: 24px;
|
||||
$spacing-3xl: 32px;
|
||||
$spacing-4xl: 40px;
|
||||
|
||||
// ============================================
|
||||
// Border Radius
|
||||
// ============================================
|
||||
$radius-sm: 3px;
|
||||
$radius-md: 4px;
|
||||
$radius-lg: 6px;
|
||||
$radius-xl: 8px;
|
||||
|
||||
// ============================================
|
||||
// Transitions
|
||||
// ============================================
|
||||
$transition-fast: 0.15s ease;
|
||||
$transition-normal: 0.2s ease;
|
||||
|
||||
// ============================================
|
||||
// Shadows
|
||||
// ============================================
|
||||
$shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
$shadow-focus: 0 0 0 1px #2271b1;
|
||||
|
||||
// ============================================
|
||||
// Typography
|
||||
// ============================================
|
||||
$font-size-xs: 11px;
|
||||
$font-size-sm: 12px;
|
||||
$font-size-base: 13px;
|
||||
$font-size-md: 14px;
|
||||
$font-size-lg: 18px;
|
||||
|
||||
$font-weight-normal: 400;
|
||||
$font-weight-medium: 500;
|
||||
$font-weight-semibold: 600;
|
||||
$font-weight-bold: 700;
|
||||
|
||||
$line-height-normal: 1.4;
|
||||
$line-height-relaxed: 1.5;
|
||||
|
||||
// ============================================
|
||||
// Component-specific
|
||||
// ============================================
|
||||
|
||||
// Table
|
||||
$table-header-bg: $color-bg-light;
|
||||
$table-row-hover: #f5f5f5;
|
||||
$table-cell-padding: $spacing-lg $spacing-xl;
|
||||
|
||||
// Badge
|
||||
$badge-padding: 4px 10px;
|
||||
$badge-font-size: $font-size-sm;
|
||||
$badge-radius: $radius-md;
|
||||
|
||||
// Button
|
||||
$button-padding: 8px $spacing-lg;
|
||||
$button-height: 36px;
|
||||
|
||||
// Input
|
||||
$input-height: 38px;
|
||||
$input-padding: 6px $spacing-md;
|
||||
$input-border-width: 1px;
|
||||
|
||||
// Breakpoints
|
||||
$breakpoint-mobile: 782px;
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* Links Page Styles (Free)
|
||||
*
|
||||
* Matches the PRO Link Genius UI design system.
|
||||
*/
|
||||
|
||||
@import 'variables';
|
||||
|
||||
// ============================================
|
||||
// PRO CTA variables & imports (required by _pro-cta.scss)
|
||||
// ============================================
|
||||
$namespace: 'rank-math';
|
||||
$rm_brand: #6666c3;
|
||||
$primary: #069de3;
|
||||
$text: #242628;
|
||||
$dark_gray: #7f868d;
|
||||
$dark-gray: #7f868d;
|
||||
$color-1: #10AC84;
|
||||
$color-3: #ed5e5e;
|
||||
$light_gray: #dadfe4;
|
||||
|
||||
@import '../../../../../../assets/admin/scss/_mixins';
|
||||
@import '../../../../../../assets/admin/scss/partials/common/_pro-cta';
|
||||
@import '../../../../../../assets/admin/scss/sidebar/_modal';
|
||||
|
||||
// ============================================
|
||||
// TabPanel wrapper reset
|
||||
// ============================================
|
||||
#rank-math-links-page-container {
|
||||
.rank-math-links-page.rank-math-wrap {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
.rank-math-tab-panel {
|
||||
width: 100%;
|
||||
|
||||
.components-tab-panel__tab-content {
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Tab content wrapper
|
||||
// ============================================
|
||||
.rank-math-tab-content {
|
||||
position: relative;
|
||||
margin-top: 16px;
|
||||
margin-left: 20px;
|
||||
margin-right: 40px;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Section card
|
||||
// ============================================
|
||||
.rank-math-section-card {
|
||||
position: relative;
|
||||
background: $color-bg-white;
|
||||
border: 1px solid $color-border;
|
||||
border-radius: $radius-md;
|
||||
margin-bottom: 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// PRO column blurring (Links tab)
|
||||
// ============================================
|
||||
.rank-math-pro-col-header {
|
||||
position: relative;
|
||||
|
||||
.rank-math-pro-badge {
|
||||
display: inline-block;
|
||||
margin-left: $spacing-xs;
|
||||
padding: 1px 5px;
|
||||
border-radius: $radius-sm;
|
||||
background: $color-warning-bg;
|
||||
color: $color-warning-text;
|
||||
font-size: $font-size-xs;
|
||||
font-weight: $font-weight-semibold;
|
||||
vertical-align: middle;
|
||||
line-height: 1.4;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
}
|
||||
|
||||
.rank-math-pro-cell {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
.rank-math-pro-blur-text {
|
||||
filter: blur(4px);
|
||||
user-select: none;
|
||||
color: $color-text-secondary;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.rank-math-pro-upgrade-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
a {
|
||||
font-size: $font-size-xs;
|
||||
color: $color-primary;
|
||||
font-weight: $font-weight-medium;
|
||||
white-space: nowrap;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Upgrade PRO Modal
|
||||
// ============================================
|
||||
.rank-math-upgrade-pro-modal {
|
||||
.rank-math-upgrade-pro-modal-body {
|
||||
text-align: center;
|
||||
padding: $spacing-lg 0;
|
||||
|
||||
.rank-math-upgrade-pro-icon {
|
||||
display: block;
|
||||
font-size: 36px;
|
||||
color: $color-warning;
|
||||
margin-bottom: $spacing-md;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: $font-size-md;
|
||||
color: $color-text-secondary;
|
||||
margin: 0 0 $spacing-lg;
|
||||
line-height: $line-height-relaxed;
|
||||
}
|
||||
|
||||
.rank-math-upgrade-pro-features {
|
||||
list-style: none;
|
||||
margin: 0 0 $spacing-xl;
|
||||
padding: 0;
|
||||
text-align: left;
|
||||
|
||||
li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-sm;
|
||||
padding: $spacing-xs 0;
|
||||
font-size: $font-size-base;
|
||||
color: $color-text-secondary;
|
||||
|
||||
&::before {
|
||||
content: '✓';
|
||||
color: $color-success;
|
||||
font-weight: $font-weight-bold;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.rank-math-upgrade-pro-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: $spacing-md;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.rank-math-upgrade-pro-btn {
|
||||
min-width: 160px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// PRO tab preview (image + CTA overlay)
|
||||
// ============================================
|
||||
.rank-math-pro-tab-preview {
|
||||
position: relative;
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
#rank-math-pro-cta {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Toggle filters layout (Links / Posts tabs)
|
||||
// ============================================
|
||||
.rank-math-table-header.has-toggle-filters {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.rank-math-table-toggle-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: stretch;
|
||||
padding: 0 $spacing-2xl 0 0;
|
||||
gap: $spacing-lg;
|
||||
flex-wrap: wrap;
|
||||
border-bottom: 1px solid $color-border;
|
||||
min-height: 52px;
|
||||
}
|
||||
|
||||
.rank-math-table-toggle-left {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 0;
|
||||
|
||||
.rank-math-toggle-button-group.is-tab-style {
|
||||
align-items: stretch;
|
||||
|
||||
.rank-math-toggle-button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-bottom: 0;
|
||||
border-bottom-width: 2px;
|
||||
margin-bottom: -1px;
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.rank-math-table-toggle-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-md;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Link type badge (Internal / External)
|
||||
// ============================================
|
||||
.rank-math-link-type-badge {
|
||||
display: inline-block;
|
||||
padding: 3px 10px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
|
||||
&.internal {
|
||||
background-color: #d4edda;
|
||||
color: #155724;
|
||||
}
|
||||
|
||||
&.external {
|
||||
background-color: #d1ecf1;
|
||||
color: #0c5460;
|
||||
}
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
/**
|
||||
* The Content Processor.
|
||||
*
|
||||
* Extract and save links from the content of a given post.
|
||||
*
|
||||
* @since 0.9.0
|
||||
* @package RankMath
|
||||
* @subpackage RankMath\Links
|
||||
* @author Rank Math <support@rankmath.com>
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
|
||||
namespace RankMath\Links;
|
||||
|
||||
use RankMath\Helpers\Str;
|
||||
use RankMath\Helper;
|
||||
use RankMath\Sitemap\Classifier;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* ContentProcessor class.
|
||||
*/
|
||||
class ContentProcessor {
|
||||
|
||||
/**
|
||||
* Singleton instance.
|
||||
*
|
||||
* @var ContentProcessor
|
||||
*/
|
||||
private static $instance = null;
|
||||
|
||||
/**
|
||||
* Link storage.
|
||||
*
|
||||
* @var Storage
|
||||
*/
|
||||
public $storage;
|
||||
|
||||
/**
|
||||
* Link classifier.
|
||||
*
|
||||
* @var Classifier
|
||||
*/
|
||||
protected $classifier;
|
||||
|
||||
/**
|
||||
* Get singleton instance.
|
||||
*
|
||||
* @return ContentProcessor
|
||||
*/
|
||||
public static function get() {
|
||||
if ( null === self::$instance ) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Constructor
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->storage = new Storage();
|
||||
$this->classifier = new Classifier( home_url() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the content.
|
||||
*
|
||||
* @param int $post_id The post ID.
|
||||
* @param string $content The content.
|
||||
*/
|
||||
public function process( $post_id, $content ) {
|
||||
/**
|
||||
* Filter: 'rank_math/links/extract' - Allow PRO to override extraction with enhanced single-pass version.
|
||||
*
|
||||
* @param null $extracted_data Default null. Return array with 'links' and 'counts' to override.
|
||||
* @param string $content The post content.
|
||||
* @param int $post_id The post ID.
|
||||
*/
|
||||
$extracted_data = apply_filters( 'rank_math/links/extract', null, $content, $post_id );
|
||||
|
||||
if ( null !== $extracted_data ) {
|
||||
// PRO provided complete extraction - use it.
|
||||
$this->process_extracted_links( $post_id, $extracted_data );
|
||||
return;
|
||||
}
|
||||
|
||||
// FREE's normal extraction continues.
|
||||
$links = $this->extract( $content );
|
||||
$counts = [
|
||||
'internal_link_count' => 0,
|
||||
'external_link_count' => 0,
|
||||
];
|
||||
|
||||
$new_links = [];
|
||||
$post_permalink = $this->normalize_link( get_permalink( $post_id ) );
|
||||
foreach ( $links as $link ) {
|
||||
$normalized_link = $this->normalize_link( $link );
|
||||
if ( $post_permalink === $normalized_link ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->process_link( $link, $new_links, $counts );
|
||||
}
|
||||
|
||||
$old_links = $this->get_stored_internal_links( $post_id );
|
||||
$this->storage->cleanup( $post_id );
|
||||
$this->storage->save_links( $post_id, $new_links );
|
||||
$this->storage->update_link_counts( $post_id, $counts, array_merge( $new_links, $old_links ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract href property values from HTML string.
|
||||
*
|
||||
* @param string $content Content to extract links from.
|
||||
*
|
||||
* @return array The extracted links.
|
||||
*/
|
||||
public function extract( $content ) {
|
||||
$links = [];
|
||||
if ( false === Str::contains( 'href', $content ) ) {
|
||||
return $links;
|
||||
}
|
||||
|
||||
$regexp = '<a\s[^>]*href=("??)([^" >]*?)\\1[^>]*>';
|
||||
|
||||
// Case insensitive & ungreedy modifiers.
|
||||
if ( preg_match_all( "/$regexp/iU", $content, $matches, PREG_SET_ORDER ) ) {
|
||||
foreach ( $matches as $match ) {
|
||||
$links[] = trim( $match[2], "'" );
|
||||
}
|
||||
}
|
||||
|
||||
return $links;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the stored internal links for the supplied post.
|
||||
*
|
||||
* @param int $post_id The post to fetch links for.
|
||||
*
|
||||
* @return Link[] List of internal links connected to the post.
|
||||
*/
|
||||
public function get_stored_internal_links( $post_id ) {
|
||||
$links = $this->storage->get_links( $post_id );
|
||||
return array_filter( $links, [ $this, 'filter_internal_link' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if link is valid.
|
||||
*
|
||||
* @param string $link Link to check.
|
||||
*
|
||||
* @return string|false Link type if valid, false if not valid.
|
||||
*/
|
||||
public function is_valid_link_type( $link ) {
|
||||
$type = false;
|
||||
if ( ! empty( $link ) && '#' !== $link[0] ) {
|
||||
$type = $this->classifier->classify( $link );
|
||||
}
|
||||
|
||||
if ( Classifier::TYPE_INTERNAL === $type && preg_match( '/\.(jpg|jpeg|png|gif|bmp|pdf|mp3|zip)$/i', $link ) ) {
|
||||
$type = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter: 'rank_math/links/link_type' - Allow developers to filter the link type.
|
||||
*/
|
||||
return apply_filters( 'rank_math/links/link_type', $type, $link );
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a link: remove trailing slash, remove fragment identifier, remove home_url.
|
||||
*
|
||||
* @param string $link The link to normalize.
|
||||
* @return string
|
||||
*/
|
||||
public function normalize_link( $link ) {
|
||||
$normalized = untrailingslashit( str_replace( home_url(), '', explode( '#', $link )[0] ) );
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter internal links.
|
||||
*
|
||||
* @param Link $link Link to test.
|
||||
*
|
||||
* @return bool True if internal, false if external.
|
||||
*/
|
||||
public function filter_internal_link( Link $link ) {
|
||||
return $link->get_type() === Classifier::TYPE_INTERNAL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the post id from a modified link.
|
||||
*
|
||||
* @param string $link Link to process.
|
||||
* @return int
|
||||
*/
|
||||
public function maybe_product_id( $link ) {
|
||||
// Early bail if Remove Base option is not enabled.
|
||||
if ( ! Helper::get_settings( 'general.wc_remove_product_base' ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$product = get_page_by_path( basename( untrailingslashit( $link ) ), OBJECT, [ 'product' ] );
|
||||
if ( ! $product ) {
|
||||
return 0;
|
||||
}
|
||||
return $product->ID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process links extracted by PRO plugin with enhanced data.
|
||||
*
|
||||
* @param int $post_id The post ID.
|
||||
* @param array $extracted_data Array with 'links' and 'counts' keys.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function process_extracted_links( $post_id, $extracted_data ) {
|
||||
$new_links = isset( $extracted_data['links'] ) ? $extracted_data['links'] : [];
|
||||
$counts = isset( $extracted_data['counts'] ) ? $extracted_data['counts'] : [
|
||||
'internal_link_count' => 0,
|
||||
'external_link_count' => 0,
|
||||
];
|
||||
|
||||
// Convert type counts to expected format.
|
||||
if ( isset( $counts['internal'] ) ) {
|
||||
$counts['internal_link_count'] = $counts['internal'];
|
||||
unset( $counts['internal'] );
|
||||
}
|
||||
if ( isset( $counts['external'] ) ) {
|
||||
$counts['external_link_count'] = $counts['external'];
|
||||
unset( $counts['external'] );
|
||||
}
|
||||
|
||||
$old_links = $this->get_stored_internal_links( $post_id );
|
||||
$this->storage->cleanup( $post_id );
|
||||
$this->storage->save_links( $post_id, $new_links );
|
||||
$this->storage->update_link_counts( $post_id, $counts, array_merge( $new_links, $old_links ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a link.
|
||||
*
|
||||
* @param string $link Link to process.
|
||||
* @param array $new_links Links to add after process.
|
||||
* @param array $counts Counts array.
|
||||
*/
|
||||
private function process_link( $link, &$new_links, &$counts ) {
|
||||
$link_type = $this->is_valid_link_type( $link );
|
||||
if ( empty( $link_type ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$target_post_id = 0;
|
||||
if ( Classifier::TYPE_INTERNAL === $link_type ) {
|
||||
$target_post_id = url_to_postid( $link );
|
||||
|
||||
if ( 0 === $target_post_id ) {
|
||||
// Maybe a product with altered url!
|
||||
$target_post_id = $this->maybe_product_id( $link );
|
||||
}
|
||||
}
|
||||
$counts[ "{$link_type}_link_count" ] += 1;
|
||||
|
||||
$new_links[] = new Link( $link, $target_post_id, $link_type );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
/**
|
||||
* The SEO Link class.
|
||||
*
|
||||
* @since 0.9.0
|
||||
* @package RankMath
|
||||
* @subpackage RankMath\Links
|
||||
* @author Rank Math <support@rankmath.com>
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
|
||||
namespace RankMath\Links;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Link class.
|
||||
*/
|
||||
class Link {
|
||||
|
||||
/**
|
||||
* Link URL.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $url;
|
||||
|
||||
/**
|
||||
* Link post ID.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $target_post_id;
|
||||
|
||||
/**
|
||||
* Link type.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $type;
|
||||
|
||||
/**
|
||||
* Extra properties for PRO features.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $extra_properties = [];
|
||||
|
||||
/**
|
||||
* Sets the properties for the object.
|
||||
*
|
||||
* @param string $url The URL.
|
||||
* @param int $target_post_id ID to the post where the link refers to.
|
||||
* @param string $type The URL type: internal or external.
|
||||
*/
|
||||
public function __construct( $url, $target_post_id, $type ) {
|
||||
$this->url = $url;
|
||||
$this->target_post_id = $target_post_id;
|
||||
$this->type = $type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic setter for dynamic properties (PRO features).
|
||||
*
|
||||
* @param string $name Property name.
|
||||
* @param mixed $value Property value.
|
||||
*/
|
||||
public function __set( $name, $value ) {
|
||||
$this->extra_properties[ $name ] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic getter for dynamic properties (PRO features).
|
||||
*
|
||||
* @param string $name Property name.
|
||||
* @return mixed Property value or null.
|
||||
*/
|
||||
public function __get( $name ) {
|
||||
return isset( $this->extra_properties[ $name ] ) ? $this->extra_properties[ $name ] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic isset for dynamic properties (PRO features).
|
||||
*
|
||||
* @param string $name Property name.
|
||||
* @return bool True if property exists.
|
||||
*/
|
||||
public function __isset( $name ) {
|
||||
return isset( $this->extra_properties[ $name ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the URL.
|
||||
*
|
||||
* @return string The URL.
|
||||
*/
|
||||
public function get_url() {
|
||||
return $this->url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the target post ID.
|
||||
*
|
||||
* @return int The target post ID.
|
||||
*/
|
||||
public function get_target_post_id() {
|
||||
return (int) $this->target_post_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the link type (internal/external).
|
||||
*
|
||||
* @return string The link type.
|
||||
*/
|
||||
public function get_type() {
|
||||
return $this->type;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
<?php
|
||||
/**
|
||||
* The Link Counter module.
|
||||
*
|
||||
* @since 0.9.0
|
||||
* @package RankMath
|
||||
* @subpackage RankMath\Links
|
||||
* @author Rank Math <support@rankmath.com>
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
|
||||
namespace RankMath\Links;
|
||||
|
||||
use WP_Post;
|
||||
use RankMath\Helper;
|
||||
use RankMath\Traits\Hooker;
|
||||
use RankMath\Admin\Database\Database;
|
||||
use RankMath\Admin\Post_Columns;
|
||||
use RankMath\Links\Admin\Admin;
|
||||
use RankMath\Links\Api\Controller;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Links class.
|
||||
*/
|
||||
class Links {
|
||||
|
||||
use Hooker;
|
||||
|
||||
/**
|
||||
* Links data.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $links_data = [];
|
||||
|
||||
/**
|
||||
* The Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->action( 'save_post', 'save_post', 10, 2 );
|
||||
$this->action( 'delete_post', 'delete_post' );
|
||||
$this->action( 'rank_math/post/column/seo_details', 'post_column_content', 11, 3 );
|
||||
$this->action( 'rank_math/links/internal_links', 'cron_job' );
|
||||
$this->action( 'rest_api_init', 'register_rest_routes' );
|
||||
|
||||
if ( is_admin() ) {
|
||||
new Admin();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register REST API routes.
|
||||
*/
|
||||
public function register_rest_routes() {
|
||||
$controller = new Controller();
|
||||
$controller->register_routes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process and save the links in a post.
|
||||
*
|
||||
* @param int $post_id The post ID to check.
|
||||
* @param WP_Post $post The post object.
|
||||
*/
|
||||
public function save_post( $post_id, $post ) {
|
||||
if ( ! $post instanceof WP_Post || ! $this->is_processable( $post ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip processing during meta-box-loader requests to avoid duplicate processing.
|
||||
// The actual save happens in the subsequent request.
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
if ( isset( $_GET['meta-box-loader'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->process( $post_id, $post->post_content );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the links data when the post is deleted.
|
||||
*
|
||||
* @param int $post_id The post ID.
|
||||
*/
|
||||
public function delete_post( $post_id ) {
|
||||
if ( ! $this->is_processable( get_post( $post_id ) ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$processor = ContentProcessor::get();
|
||||
|
||||
// Get links to update linked objects.
|
||||
$links = $processor->get_stored_internal_links( $post_id );
|
||||
|
||||
// Remove all links for this post.
|
||||
$processor->storage->cleanup( $post_id );
|
||||
|
||||
// Update link counts.
|
||||
$processor->storage->update_link_counts( $post_id, [], $links );
|
||||
}
|
||||
|
||||
/**
|
||||
* Post column content.
|
||||
*
|
||||
* @param int $post_id Post ID.
|
||||
* @param array $post_data Current post SEO data.
|
||||
* @param array $data All posts SEO data.
|
||||
*/
|
||||
public function post_column_content( $post_id, $post_data, $data ) {
|
||||
if ( ! Post_Columns::is_post_indexable( $post_id ) || empty( $data ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( empty( $this->links_data ) ) {
|
||||
$this->get_links_data( array_keys( $data ) );
|
||||
}
|
||||
|
||||
$counts = ! empty( $this->links_data[ $post_id ] ) ? $this->links_data[ $post_id ] : (object) [
|
||||
'internal_link_count' => 0,
|
||||
'external_link_count' => 0,
|
||||
'incoming_link_count' => 0,
|
||||
];
|
||||
|
||||
/**
|
||||
* Filter to customize link count display in post list.
|
||||
*
|
||||
* Allows other plugins (like Rank Math PRO) to make link counts clickable.
|
||||
*
|
||||
* @param string $html The HTML output for link counts.
|
||||
* @param int $post_id Post ID.
|
||||
* @param object $counts Link counts object with internal_link_count, external_link_count, incoming_link_count.
|
||||
*/
|
||||
$output = $this->do_filter(
|
||||
'links/post_column_display',
|
||||
$this->get_default_link_count_html( $post_id, $counts ),
|
||||
$post_id,
|
||||
$counts
|
||||
);
|
||||
|
||||
echo wp_kses_post( $output );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default HTML for link counts display.
|
||||
*
|
||||
* @param int $post_id Post ID.
|
||||
* @param object $counts Link counts object.
|
||||
*
|
||||
* @return string HTML output.
|
||||
*/
|
||||
private function get_default_link_count_html( $post_id, $counts ) {
|
||||
ob_start();
|
||||
?>
|
||||
<span class="rank-math-column-display rank-math-link-count">
|
||||
<strong><?php esc_html_e( 'Links: ', 'seo-by-rank-math' ); ?></strong>
|
||||
<?php
|
||||
/**
|
||||
* Filter to customize individual link count item display.
|
||||
*
|
||||
* @param string $html The HTML for this count item.
|
||||
* @param string $type Link type: 'internal', 'external', or 'incoming'.
|
||||
* @param int $count The count value.
|
||||
* @param int $post_id Post ID.
|
||||
* @param object $counts All link counts object.
|
||||
*/
|
||||
echo wp_kses_post( $this->get_link_count_item_html( 'internal', $counts->internal_link_count, $post_id ) );
|
||||
?>
|
||||
<span class="divider"></span>
|
||||
<?php
|
||||
echo wp_kses_post( $this->get_link_count_item_html( 'external', $counts->external_link_count, $post_id ) );
|
||||
?>
|
||||
<span class="divider"></span>
|
||||
<?php
|
||||
echo wp_kses_post( $this->get_link_count_item_html( 'incoming', $counts->incoming_link_count, $post_id ) );
|
||||
?>
|
||||
</span>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get HTML for a single link count item.
|
||||
*
|
||||
* Renders as a clickable link when count > 0, plain span otherwise.
|
||||
*
|
||||
* @param string $type Link type: 'internal', 'external', or 'incoming'.
|
||||
* @param int $count The count value.
|
||||
* @param int $post_id Post ID (used to build the Links page URL).
|
||||
*
|
||||
* @return string HTML output.
|
||||
*/
|
||||
private function get_link_count_item_html( $type, $count, $post_id ) {
|
||||
$icons = [
|
||||
'internal' => 'dashicons-admin-links',
|
||||
'external' => 'dashicons-external',
|
||||
'incoming' => 'dashicons-external internal',
|
||||
];
|
||||
|
||||
$titles = [
|
||||
'internal' => __( 'Internal Links', 'seo-by-rank-math' ),
|
||||
'external' => __( 'External Links', 'seo-by-rank-math' ),
|
||||
'incoming' => __( 'Incoming Links', 'seo-by-rank-math' ),
|
||||
];
|
||||
|
||||
$inner = sprintf(
|
||||
'<span class="dashicons %1$s"></span><span>%2$s</span>',
|
||||
esc_attr( $icons[ $type ] ),
|
||||
esc_html( $count )
|
||||
);
|
||||
|
||||
if ( empty( $count ) ) {
|
||||
return sprintf(
|
||||
'<span class="rank-math-link-count-item" data-link-type="%1$s" title="%2$s">%3$s</span>',
|
||||
esc_attr( $type ),
|
||||
esc_attr( $titles[ $type ] ),
|
||||
$inner
|
||||
);
|
||||
}
|
||||
|
||||
$params = 'incoming' === $type
|
||||
? [
|
||||
'target_post_id' => absint( $post_id ),
|
||||
'link_type' => 'internal',
|
||||
]
|
||||
: [
|
||||
'source_id' => absint( $post_id ),
|
||||
'link_type' => $type,
|
||||
];
|
||||
|
||||
$url = Helper::get_admin_url( 'links-page' ) . '#links?' . http_build_query( $params );
|
||||
|
||||
return sprintf(
|
||||
'<a href="%1$s" class="rank-math-link-count-item rank-math-link-count-clickable" data-link-type="%2$s" title="%3$s">%4$s</a>',
|
||||
esc_url( $url ),
|
||||
esc_attr( $type ),
|
||||
esc_attr( $titles[ $type ] ),
|
||||
$inner
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process old posts if this is an old installation.
|
||||
*/
|
||||
public function cron_job() {
|
||||
$post_types = Helper::get_accessible_post_types();
|
||||
unset( $post_types['attachment'] );
|
||||
|
||||
$posts = get_posts(
|
||||
[
|
||||
'post_type' => array_keys( $post_types ),
|
||||
'post_status' => [ 'publish', 'future' ],
|
||||
'meta_query' => [
|
||||
[
|
||||
'key' => 'rank_math_internal_links_processed',
|
||||
'compare' => 'NOT EXISTS',
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
// Early Bail.
|
||||
if ( empty( $posts ) ) {
|
||||
wp_clear_scheduled_hook( 'rank_math/links/internal_links' );
|
||||
return;
|
||||
}
|
||||
|
||||
// Process.
|
||||
foreach ( $posts as $post ) {
|
||||
$this->save_post( $post->ID, $post );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a post (static method for use by PRO plugin).
|
||||
*
|
||||
* @param int $post_id The post ID.
|
||||
* @param WP_Post $post The post object.
|
||||
*/
|
||||
public static function process_post_links( $post_id, $post ) {
|
||||
if ( ! $post instanceof \WP_Post || ! self::is_post_processable( $post ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::process( $post_id, $post->post_content );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the post is processable (static method for use by PRO plugin).
|
||||
*
|
||||
* @param WP_Post $post The post object.
|
||||
* @return bool True if processable.
|
||||
*/
|
||||
public static function is_post_processable( $post ) {
|
||||
/**
|
||||
* Filter to prevent processing the post.
|
||||
*
|
||||
* @param boolean $value Whether to process the post.
|
||||
* @param WP_POST $post The Post object.
|
||||
*/
|
||||
if ( wp_is_post_revision( $post->ID ) || ! apply_filters( 'rank_math/links/process_post', true, $post ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( in_array( $post->post_status, [ 'auto-draft', 'trash' ], true ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$post_types = Helper::get_accessible_post_types();
|
||||
unset( $post_types['attachment'] );
|
||||
|
||||
return isset( $post_types[ $post->post_type ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the content for a given post.
|
||||
*
|
||||
* @param int $post_id The post ID.
|
||||
* @param string $content The content.
|
||||
*/
|
||||
private static function process( $post_id, $content ) {
|
||||
/**
|
||||
* Filter to change the content passed to the Link processor.
|
||||
*
|
||||
* @param string $content Post content.
|
||||
* @param int $post_id Post ID.
|
||||
*/
|
||||
$content = apply_filters( 'rank_math/links/content', $content, $post_id );
|
||||
$content = str_replace( ']]>', ']]>', $content );
|
||||
|
||||
$processor = ContentProcessor::get();
|
||||
$processor->process( $post_id, $content );
|
||||
update_post_meta( $post_id, 'rank_math_internal_links_processed', true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the post is processable.
|
||||
*
|
||||
* @param WP_Post $post The post object.
|
||||
*
|
||||
* @return bool True if processable.
|
||||
*/
|
||||
private function is_processable( $post ) {
|
||||
/**
|
||||
* Filter to prevent processing the post.
|
||||
*
|
||||
* @param boolean $value Whether to process the post.
|
||||
* @param WP_POST $post The Post object.
|
||||
*/
|
||||
if ( wp_is_post_revision( $post->ID ) || ! $this->do_filter( 'links/process_post', true, $post ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( in_array( $post->post_status, [ 'auto-draft', 'trash' ], true ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$post_types = Helper::get_accessible_post_types();
|
||||
unset( $post_types['attachment'] );
|
||||
|
||||
return isset( $post_types[ $post->post_type ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get links data by post id.
|
||||
*
|
||||
* @param array $post_ids The post ids.
|
||||
*/
|
||||
private function get_links_data( $post_ids ) {
|
||||
$results = Database::table( 'rank_math_internal_meta' )->select( '*' )->whereIn( 'object_id', $post_ids )->groupBy( 'object_id' )->get();
|
||||
$this->links_data = array_combine( array_column( $results, 'object_id' ), $results );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
/**
|
||||
* The DB interface.
|
||||
*
|
||||
* @since 0.9.0
|
||||
* @package RankMath
|
||||
* @subpackage RankMath\Links
|
||||
* @author Rank Math <support@rankmath.com>
|
||||
*/
|
||||
|
||||
namespace RankMath\Links;
|
||||
|
||||
use RankMath\Helpers\DB as DB_Helper;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Storage class.
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
class Storage {
|
||||
|
||||
/**
|
||||
* Get query builder.
|
||||
*
|
||||
* @return \RankMath\Admin\Database\Query_Builder
|
||||
*/
|
||||
public function table() {
|
||||
return \RankMath\Helpers\DB::query_builder( 'rank_math_internal_links' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all data for a given post.
|
||||
*
|
||||
* @param int $post_id The post ID to remove the records for.
|
||||
*
|
||||
* @return int|false The number of rows updated, or false on error.
|
||||
*/
|
||||
public function cleanup( $post_id ) {
|
||||
return $this->table()->where( 'post_id', $post_id )->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get array of links from the database for given post.
|
||||
*
|
||||
* @param int $post_id The post to get the links for.
|
||||
*
|
||||
* @return Link[] The links array.
|
||||
*/
|
||||
public function get_links( $post_id ) {
|
||||
$links = [];
|
||||
$results = $this->table()
|
||||
->select( [ 'url', 'post_id', 'target_post_id', 'type' ] )
|
||||
->where( 'post_id', $post_id )
|
||||
->get();
|
||||
|
||||
foreach ( $results as $link ) {
|
||||
$links[] = new Link( $link->url, $link->target_post_id, $link->type );
|
||||
}
|
||||
|
||||
return $links;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save links for a post.
|
||||
*
|
||||
* @param integer $post_id The post ID to save.
|
||||
* @param Link[] $links The links to save.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function save_links( $post_id, array $links ) {
|
||||
// Reduces lock count from N to 1, reducing lock duration by ~95%.
|
||||
if ( empty( $links ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter: Allow extensions to override link saving behavior.
|
||||
*
|
||||
* Return non-null to bypass default save and handle it yourself.
|
||||
*
|
||||
* @param null|bool $override Whether to override. Return true to bypass default save.
|
||||
* @param int $post_id Post ID.
|
||||
* @param array $links Array of Link objects to save.
|
||||
* @param Storage $storage Storage instance for table access.
|
||||
*/
|
||||
$override = apply_filters( 'rank_math/links/save_links', null, $post_id, $links, $this );
|
||||
if ( null !== $override ) {
|
||||
return;
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'rank_math_internal_links';
|
||||
|
||||
// Build VALUES for batch INSERT.
|
||||
$values = [];
|
||||
foreach ( $links as $link ) {
|
||||
$values[] = $wpdb->prepare(
|
||||
'(%s, %d, %d, %s)',
|
||||
$link->get_url(),
|
||||
$post_id,
|
||||
$link->get_target_post_id(),
|
||||
$link->get_type()
|
||||
);
|
||||
}
|
||||
|
||||
// Execute single INSERT with multiple VALUES.
|
||||
$wpdb->query(
|
||||
"INSERT INTO {$table} (url, post_id, target_post_id, type) VALUES " . implode( ', ', $values )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the link counts for a post and its referenced posts.
|
||||
*
|
||||
* @param int $post_id Post to update.
|
||||
* @param int|null $counts Links count.
|
||||
* @param Link[] $links Links to update incoming link count.
|
||||
*/
|
||||
public function update_link_counts( $post_id, $counts, array $links ) {
|
||||
$counts = wp_parse_args(
|
||||
$counts,
|
||||
[
|
||||
'internal_link_count' => 0,
|
||||
'external_link_count' => 0,
|
||||
]
|
||||
);
|
||||
|
||||
$this->save_meta_data( $post_id, $counts );
|
||||
$this->update_incoming_links( $post_id, $links );
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the incoming link count.
|
||||
*
|
||||
* @param int $post_id Post which is processed.
|
||||
* @param Link[] $links Links we need to update the incoming link count of.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function update_incoming_links( $post_id, $links ) {
|
||||
$post_ids = $this->get_internal_post_ids( $links );
|
||||
$post_ids = array_merge( [ $post_id ], $post_ids );
|
||||
$this->update_incoming_link_count( $post_ids );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get post IDs from the link objects.
|
||||
*
|
||||
* @param Link[] $links Links we need to update the incoming link count of.
|
||||
*
|
||||
* @return int[] List of post IDs.
|
||||
*/
|
||||
protected function get_internal_post_ids( $links ) {
|
||||
$post_ids = [];
|
||||
foreach ( $links as $link ) {
|
||||
$post_ids[] = $link->get_target_post_id();
|
||||
}
|
||||
|
||||
return array_filter( $post_ids );
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the incoming link count.
|
||||
*
|
||||
* @param array $post_ids The posts to update the link count for.
|
||||
*/
|
||||
public function update_incoming_link_count( array $post_ids ) {
|
||||
$results = $this->table()
|
||||
->selectCount( 'id', 'incoming' )
|
||||
->select( 'target_post_id as post_id' )
|
||||
->whereIn( 'target_post_id', $post_ids )
|
||||
->groupBy( 'target_post_id' )->get();
|
||||
|
||||
$post_ids_non_zero = [];
|
||||
foreach ( $results as $result ) {
|
||||
$this->save_meta_data( $result->post_id, [ 'incoming_link_count' => $result->incoming ] );
|
||||
$post_ids_non_zero[] = $result->post_id;
|
||||
}
|
||||
|
||||
$post_ids_zero = array_diff( $post_ids, $post_ids_non_zero );
|
||||
foreach ( $post_ids_zero as $post_id ) {
|
||||
$this->save_meta_data( $post_id, [ 'incoming_link_count' => 0 ] );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the link count to the database.
|
||||
*
|
||||
* Previous SELECT-then-INSERT/UPDATE pattern caused deadlocks when
|
||||
* multiple posts linked to the same target post.
|
||||
*
|
||||
* @param int $post_id The ID to save the link count for.
|
||||
* @param array $meta_data The total amount of links.
|
||||
*/
|
||||
public function save_meta_data( $post_id, array $meta_data ) {
|
||||
global $wpdb;
|
||||
|
||||
$table = $wpdb->prefix . 'rank_math_internal_meta';
|
||||
|
||||
// Build field assignments for ON DUPLICATE KEY UPDATE.
|
||||
$allowed_keys = [ 'incoming_link_count', 'internal_link_count', 'external_link_count' ];
|
||||
$update_parts = [];
|
||||
foreach ( $meta_data as $key => $value ) {
|
||||
if ( ! in_array( $key, $allowed_keys, true ) ) {
|
||||
continue;
|
||||
}
|
||||
$update_parts[] = $wpdb->prepare( "{$key} = %d", $value );
|
||||
}
|
||||
|
||||
// Single operation eliminates SELECT-then-INSERT gap.
|
||||
return $wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"INSERT INTO {$table}
|
||||
(object_id, incoming_link_count, internal_link_count, external_link_count)
|
||||
VALUES (%d, %d, %d, %d)
|
||||
ON DUPLICATE KEY UPDATE " . implode( ', ', $update_parts ),
|
||||
$post_id,
|
||||
$meta_data['incoming_link_count'] ?? 0,
|
||||
$meta_data['internal_link_count'] ?? 0,
|
||||
$meta_data['external_link_count'] ?? 0
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user