Skip to content

Instantly share code, notes, and snippets.

@abidkakkur11
Created October 29, 2026 13:37
Show Gist options
  • Select an option

  • Save abidkakkur11/bb4edca04edb628cb8b89362cace636a to your computer and use it in GitHub Desktop.

Select an option

Save abidkakkur11/bb4edca04edb628cb8b89362cace636a to your computer and use it in GitHub Desktop.
WordPress Yoast SEO Migration Comparator – Elementor to Bricks

WordPress Yoast SEO Migration Comparator

A PHP-based WordPress utility for exporting, comparing, and selectively migrating Yoast SEO metadata from an existing website to a new WordPress installation.

Designed primarily for Elementor-to-Bricks Builder migrations, this tool helps identify missing or mismatched SEO metadata before a redesigned website goes live.

The utility consists of two separate snippets:

  1. Source Site Exporter — exports page information, SEO metadata, and extracted content from the original WordPress website into a JSON file.
  2. Staging Site Comparator & Importer — imports the JSON file, matches pages against the staging website, displays differences in an admin dashboard, and allows administrators to selectively update approved SEO fields.

The workflow is designed around reviewing differences before making changes rather than blindly importing metadata.

Features

1. Export data from the source website

The source-site snippet generates a downloadable JSON export containing page information and SEO metadata.

Depending on the exporter configuration, the export includes:

  • WordPress post type
  • Page slug and URL path
  • Parent page path
  • Page title and publication status
  • Excerpt and page template
  • Featured image filename
  • Extracted text from Elementor data and WordPress content
  • Yoast SEO title
  • Yoast meta description
  • Yoast focus keyphrase

The exporter is intended to be read-only. It does not modify the source pages or their SEO metadata.

2. Match pages between websites

The staging comparator matches exported records with pages on the destination website using:

  • Post type
  • URL path, including the parent-page hierarchy where available

This is more reliable than matching pages by title alone, since titles can change during a redesign.

The dashboard identifies pages that match, pages with SEO differences, pages with content differences, and pages that are missing or ambiguous.

Important: Matching depends on consistent URL paths. If the destination website has different slugs or page hierarchies, those pages may require manual review.

3. Compare Yoast SEO metadata

The importer focuses on these three Yoast SEO fields:

Field WordPress meta key Purpose
SEO title _yoast_wpseo_title Search result title
Meta description _yoast_wpseo_metadesc Search result description
Focus keyphrase _yoast_wpseo_focuskw Keyphrase used by Yoast's SEO analysis

The dashboard displays the source and staging values so that administrators can review differences before updating the destination website.

Other page information is used for comparison and context. The tool is not intended to migrate page layouts or replace the destination page content.

4. Review page content differences

The tool extracts and compares text from available page content and builder data to help identify pages that may have changed during migration.

This is useful for checking whether the source page and its replacement contain broadly similar text.

Content comparison is approximate. Differences in builder storage, shortcodes, dynamic content, formatting, widgets, and generated markup can affect the result. A content difference does not necessarily indicate a problem.

5. Selective updates with confirmation

The staging dashboard allows administrators to:

  • Search and filter comparison results
  • Review SEO differences
  • Inspect source and destination values
  • Select individual matched pages
  • Select visible matched pages in bulk
  • Confirm the intended update before proceeding

Only selected pages are processed. This helps avoid overwriting metadata across the entire website unintentionally.

6. Preserve existing metadata before updates

Before changing a page's SEO metadata, the importer stores the previous values of the three supported Yoast fields in the page's _ysmcp_previous_yoast_metadata post meta.

This provides a record of the previous values for recovery or manual restoration.

Backup limitation: The current implementation stores a previous-value snapshot rather than providing a complete backup-management or one-click rollback interface. Repeated updates may replace the previous snapshot. Keep a separate database backup before running bulk changes.

7. Avoid clearing destination values with empty source fields

Empty source SEO values are not intended to erase existing destination metadata.

This is important because an empty field on the source website may be intentional, unavailable, or not configured. The migration process should not automatically interpret an empty value as an instruction to delete a destination value.

8. Admin dashboard

The staging comparator provides an interface under:

WordPress Admin → Tools → SEO Migration Comparator

The dashboard includes comparison summaries, filtering, search, per-page details, selection controls, and a confirmation step before updates.

The source exporter is available under:

WordPress Admin → Tools → Yoast Migration Export

Exact menu labels may vary if the snippets have been customized.

Requirements

  • WordPress installation on both the source and destination websites
  • Yoast SEO installed on the relevant websites
  • Code Snippets plugin, or an equivalent method for safely managing PHP snippets
  • Permission to manage the relevant WordPress pages and metadata
  • A database backup of the destination website before importing
  • Access to the source-site JSON export

The snippets should be reviewed against the current WordPress, Yoast SEO, and PHP versions before production use.

Installation

Step 1: Install the source exporter

  1. Open the WordPress admin dashboard of the original website.
  2. Install or open the Code Snippets plugin.
  3. Create a new PHP snippet.
  4. Paste the Source Site Exporter code.
  5. Save and activate it on the source website only.
  6. Open Tools → Yoast Migration Export.
  7. Generate and download the JSON export.

The export file contains website content and SEO metadata. Store it securely and do not publish it publicly if it includes confidential information.

Step 2: Install the staging comparator

  1. Open the WordPress admin dashboard of the destination staging website.
  2. Create a new PHP snippet in Code Snippets.
  3. Paste the SEO Migration Comparator & Importer code.
  4. Save and activate it on the staging website only.
  5. Confirm that the staging protection checks recognize the destination as a staging environment.
  6. Open Tools → SEO Migration Comparator.

Do not activate the importer on the live production website.

Step 3: Verify staging protection

The comparator includes a staging-environment check. Its behavior depends on the WordPress environment configuration and recognized staging hostnames.

Where appropriate, configure the staging website's wp-config.php with:

define( 'WP_ENVIRONMENT_TYPE', 'staging' );

If the constant is already defined, edit the existing definition rather than adding a duplicate.

The environment check is a precaution, not a complete security boundary. Verify that it correctly identifies your staging website before enabling any update workflow.

Step 4: Import the JSON export

  1. Open the comparator dashboard on staging.
  2. Upload the JSON file generated by the source exporter.
  3. Allow the tool to validate and process the export.
  4. Review the summary and comparison results.
  5. Investigate missing or ambiguous page matches before making changes.

Step 5: Review and update

  1. Filter for SEO differences.
  2. Inspect the source and destination SEO values for each relevant page.
  3. Check content differences when they may indicate that the wrong pages were matched or that content was missed during migration.
  4. Select only the pages you want to update.
  5. Review the confirmation prompt.
  6. Confirm the update.

Afterward, review the affected pages in WordPress and verify their SEO fields in Yoast.

Recommended migration workflow

  1. Back up the destination database.
  2. Complete the page migration and confirm the intended destination slugs.
  3. Export the source site's metadata.
  4. Upload the export to the staging comparator.
  5. Review missing and ambiguous matches first.
  6. Review SEO title, meta description, and focus keyphrase differences.
  7. Review significant content differences.
  8. Update only the approved pages.
  9. Check the resulting metadata in the WordPress editor.
  10. Test important URLs and SEO output before deploying staging to production.

Scope and limitations

This tool is designed for page-level metadata comparison and selective migration. It should not be treated as a complete website migration solution.

  • Supported SEO updates: Yoast SEO title, meta description, and focus keyphrase.
  • Page matching: Based on post type and URL path; changed slugs and parent paths can prevent automatic matching.
  • Content comparison: Approximate text comparison, not a visual layout or full HTML comparison.
  • Builder support: Extracted content depends on what is available in WordPress content and builder metadata. Elementor and Bricks may store data differently.
  • Post types: The current implementation focuses on WordPress pages. Posts and custom post types may need additional configuration.
  • Other SEO metadata: Canonical URLs, robots directives, social metadata, schema settings, redirects, breadcrumbs, and other SEO fields are not automatically migrated by the three-field update process.
  • Page layouts: The importer does not migrate Elementor layouts to Bricks layouts.
  • Rollback: Previous metadata is stored, but a dedicated rollback interface is not included.
  • Production safety: The staging guard reduces accidental use but does not replace a backup, code review, and testing.

Security considerations

  • Run the importer only on a controlled staging website.
  • Keep WordPress and its plugins updated.
  • Restrict access to trusted administrators.
  • Use the provided capability checks and nonce verification.
  • Do not share exported JSON files publicly.
  • Review imported data before applying changes.
  • Back up the database before bulk updates.
  • Inspect the code before installing it on a site that contains sensitive content.

Testing checklist

Before relying on the tool for a large migration, test it with a small selection of pages.

  • The source exporter runs without changing source data.
  • The JSON export downloads and contains the expected pages.
  • Pages with matching paths are matched correctly.
  • Pages with changed paths are flagged for review.
  • SEO title differences appear correctly.
  • Meta description differences appear correctly.
  • Focus keyphrase differences appear correctly.
  • Empty source fields do not clear destination metadata.
  • Content differences are displayed as expected.
  • Unselected pages remain unchanged.
  • Selected pages update only the three supported fields.
  • Previous metadata is backed up before changes.
  • The confirmation step works as intended.
  • The importer refuses to run when the staging safety check fails.
  • The updated pages are reviewed in Yoast and on the front end.

Troubleshooting

Pages appear as missing

Check whether the source and destination use the same slug, post type, and parent-page path. Review the JSON export to confirm that the expected source record exists.

Multiple pages are ambiguous

Duplicate paths or multiple records that resolve to the same matching key need manual investigation. Avoid applying updates until the matching issue is resolved.

SEO values appear empty

Confirm that the source pages have the expected Yoast metadata and that the export includes the correct meta keys. Empty source values are not meant to clear destination values.

Content comparison reports differences

Builder data can contain different formatting, shortcodes, dynamic elements, or generated content. Inspect the actual page content before deciding whether the difference is significant.

The importer refuses to run on staging

Check WP_ENVIRONMENT_TYPE, the staging hostname, and the snippet's environment guard. Do not bypass the protection without understanding why the environment was not recognized.

An update does not appear on the front end

Verify the metadata in the WordPress editor, then clear relevant page, server, and CDN caches. Confirm that Yoast is generating the expected output and that no other plugin or theme code overrides it.

Disclaimer

This utility is provided as a migration aid. Review the code, test on staging, and keep a database backup before applying updates. No automatic matcher or content comparison can guarantee that every page is mapped correctly.

Use it as a review-first workflow to help reduce manual effort and migration errors, not as a substitute for final SEO validation.

/**
* Yoast Migration Comparator — Admin Dashboard
*
* Install on STAGING only using Code Snippets.
* Compatible with the JSON export from Source Snippet.
*
* Updates only:
* _yoast_wpseo_title
* _yoast_wpseo_metadesc
* _yoast_wpseo_focuskw
*/
defined( 'ABSPATH' ) || exit;
/* ---------- Environment guard ---------- */
function ysmcp_is_staging() {
$environment = function_exists( 'wp_get_environment_type' )
? wp_get_environment_type()
: 'production';
if ( in_array( $environment, [ 'staging', 'local' ], true ) ) {
return true;
}
$host = strtolower(
(string) wp_parse_url( home_url(), PHP_URL_HOST )
);
return in_array( $host, [ 'localhost', '127.0.0.1' ], true )
|| substr( $host, -6 ) === '.local'
|| strpos( $host, 'staging.' ) === 0
|| strpos( $host, '.staging.' ) !== false;
}
/* ---------- Admin menu ---------- */
add_action( 'admin_menu', function () {
add_management_page(
'Yoast Migration Comparator',
'SEO Migration Comparator',
'manage_options',
'ysmc-stage-comparator',
'ysmcp_render_dashboard'
);
});
/* ---------- Comparison helpers ---------- */
function ysmcp_normalize_text( $value ) {
$value = html_entity_decode(
wp_strip_all_tags( (string) $value ),
ENT_QUOTES | ENT_HTML5,
'UTF-8'
);
return trim( (string) preg_replace( '/\s+/u', ' ', $value ) );
}
function ysmcp_collect_text( $data, &$output = [] ) {
if ( ! is_array( $data ) ) {
return $output;
}
$keys = [
'title', 'heading', 'text', 'editor',
'text_editor', 'content', 'description',
'button_text', 'label',
];
foreach ( $data as $key => $value ) {
if (
is_string( $value ) &&
in_array( (string) $key, $keys, true )
) {
$text = ysmcp_normalize_text( $value );
if ( '' !== $text ) {
$output[] = $text;
}
} elseif ( is_array( $value ) ) {
ysmcp_collect_text( $value, $output );
}
}
return $output;
}
function ysmcp_parent_path( $post ) {
if ( ! $post->post_parent ) {
return '';
}
$parent = get_post( $post->post_parent );
return $parent ? get_page_uri( $parent ) : '';
}
function ysmcp_record( $post ) {
$bricks = get_post_meta(
$post->ID,
'_bricks_page_content_2',
true
);
$texts = [];
if ( is_array( $bricks ) ) {
ysmcp_collect_text( $bricks, $texts );
}
$content = ysmcp_normalize_text( $post->post_content );
if ( '' !== $content ) {
$texts[] = $content;
}
$texts = array_values( array_unique( $texts ) );
$parent = $post->post_parent
? get_post( $post->post_parent )
: null;
$thumbnail_id = get_post_thumbnail_id( $post->ID );
$file = $thumbnail_id
? get_post_meta( $thumbnail_id, '_wp_attached_file', true )
: '';
return [
'post_type' => $post->post_type,
'path' => get_page_uri( $post ),
'parent_path' => $parent ? get_page_uri( $parent ) : '',
'title' => $post->post_title,
'status' => $post->post_status,
'excerpt' => $post->post_excerpt,
'template' => (string) get_post_meta(
$post->ID, '_wp_page_template', true
),
'featured_image' => $file ? basename( $file ) : '',
'content_text' => implode( ' | ', $texts ),
'seo' => [
'_yoast_wpseo_title' => (string) get_post_meta(
$post->ID, '_yoast_wpseo_title', true
),
'_yoast_wpseo_metadesc' => (string) get_post_meta(
$post->ID, '_yoast_wpseo_metadesc', true
),
'_yoast_wpseo_focuskw' => (string) get_post_meta(
$post->ID, '_yoast_wpseo_focuskw', true
),
],
];
}
function ysmcp_index_pages() {
$posts = get_posts( [
'post_type' => 'page',
'post_status' => [
'publish', 'draft', 'private', 'pending', 'future',
],
'posts_per_page' => -1,
'orderby' => 'ID',
'order' => 'ASC',
] );
$index = [];
foreach ( $posts as $post ) {
$key = $post->post_type . '|' . get_page_uri( $post );
if ( array_key_exists( $key, $index ) ) {
$index[ $key ] = false;
} else {
$index[ $key ] = $post;
}
}
return $index;
}
function ysmcp_compare( $source, $destination ) {
$fields = [
'title', 'parent_path', 'status', 'excerpt',
'template', 'featured_image',
];
$diff = [];
foreach ( $fields as $field ) {
$diff[ $field ] = (string) ( $source[ $field ] ?? '' )
=== (string) ( $destination[ $field ] ?? '' );
}
$diff['content_text'] = hash(
'sha256',
ysmcp_normalize_text( $source['content_text'] ?? '' )
) === hash(
'sha256',
ysmcp_normalize_text( $destination['content_text'] ?? '' )
);
foreach ( [
'_yoast_wpseo_title',
'_yoast_wpseo_metadesc',
'_yoast_wpseo_focuskw',
] as $field ) {
$diff[ $field ] = (string) ( $source['seo'][ $field ] ?? '' )
=== (string) ( $destination['seo'][ $field ] ?? '' );
}
return $diff;
}
function ysmcp_seo_diff_count( $diff ) {
$count = 0;
foreach ( [
'_yoast_wpseo_title',
'_yoast_wpseo_metadesc',
'_yoast_wpseo_focuskw',
] as $field ) {
if ( empty( $diff[ $field ] ) ) {
$count++;
}
}
return $count;
}
/* ---------- Import and update actions ---------- */
function ysmcp_dashboard_url( $token = '' ) {
$url = add_query_arg(
'page',
'ysmc-stage-comparator',
admin_url( 'tools.php' )
);
return $token
? add_query_arg( 'token', $token, $url )
: $url;
}
function ysmcp_redirect( $url ) {
wp_safe_redirect( $url );
exit;
}
function ysmcp_handle_upload() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Permission denied.' );
}
check_admin_referer( 'ysmcp_upload' );
if (
empty( $_FILES['ysmc_json']['tmp_name'] ) ||
! empty( $_FILES['ysmc_json']['error'] )
) {
wp_die( 'Please select a valid JSON export.' );
}
if ( (int) $_FILES['ysmc_json']['size'] > 10 * MB_IN_BYTES ) {
wp_die( 'The JSON file exceeds the 10 MB limit.' );
}
$raw = file_get_contents( $_FILES['ysmc_json']['tmp_name'] );
$data = json_decode( $raw, true );
if (
! is_array( $data ) ||
( $data['format'] ?? '' ) !== 'ysmc-export' ||
(int) ( $data['version'] ?? 0 ) !== 1 ||
! is_array( $data['pages'] ?? null )
) {
wp_die( 'Invalid or unsupported export file.' );
}
// Validate every record before accepting the export.
foreach ( $data['pages'] as $record ) {
if (
! is_array( $record ) ||
! isset( $record['path'], $record['post_type'], $record['seo'] ) ||
! is_array( $record['seo'] )
) {
wp_die( 'The export contains an invalid page record.' );
}
}
$token = wp_generate_password( 32, false, false );
set_transient( 'ysmcp_' . $token, $data, HOUR_IN_SECONDS );
ysmcp_redirect( ysmcp_dashboard_url( $token ) );
}
add_action( 'admin_post_ysmcp_upload', 'ysmcp_handle_upload' );
function ysmcp_handle_update() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Permission denied.' );
}
check_admin_referer( 'ysmcp_update' );
if ( ! ysmcp_is_staging() ) {
wp_die( 'Updates blocked. This installation is not recognized as staging or local.' );
}
if ( ( $_POST['confirm'] ?? '' ) !== 'yes' ) {
wp_die( 'Explicit confirmation is required.' );
}
$token = sanitize_text_field(
wp_unslash( $_POST['token'] ?? '' )
);
$data = get_transient( 'ysmcp_' . $token );
if ( ! is_array( $data ) ) {
wp_die( 'The import session expired. Please upload the JSON again.' );
}
$selected = array_unique( array_map(
'absint',
(array) ( $_POST['selected'] ?? [] )
) );
$index = ysmcp_index_pages();
$updated = 0;
$skipped = 0;
$allowed_fields = [
'_yoast_wpseo_title',
'_yoast_wpseo_metadesc',
'_yoast_wpseo_focuskw',
];
foreach ( $selected as $i ) {
if ( ! isset( $data['pages'][ $i ] ) ) {
$skipped++;
continue;
}
$source = $data['pages'][ $i ];
$key = $source['post_type'] . '|' . $source['path'];
$post = $index[ $key ] ?? null;
if ( ! $post || ! $post instanceof WP_Post ) {
$skipped++;
continue;
}
// Re-check immediately before writing.
if ( 'page' !== $post->post_type ) {
$skipped++;
continue;
}
// Store previous values for later manual recovery.
$backup = [];
foreach ( $allowed_fields as $field ) {
$backup[ $field ] = get_post_meta(
$post->ID, $field, true
);
}
update_post_meta(
$post->ID,
'_ysmcp_previous_yoast_metadata',
[
'backup_time' => gmdate( 'c' ),
'source_url' => esc_url_raw( $data['source_url'] ?? '' ),
'values' => $backup,
]
);
foreach ( $allowed_fields as $field ) {
$value = (string) ( $source['seo'][ $field ] ?? '' );
// Preserve destination values for blank source fields.
if ( '' === trim( $value ) ) {
continue;
}
update_post_meta(
$post->ID,
$field,
sanitize_text_field( $value )
);
}
$updated++;
}
// One-time result notice.
$result = [
'updated' => $updated,
'skipped' => $skipped,
];
set_transient(
'ysmcp_result_' . get_current_user_id(),
$result,
MINUTE_IN_SECONDS
);
ysmcp_redirect( ysmcp_dashboard_url( $token ) );
}
add_action( 'admin_post_ysmcp_update', 'ysmcp_handle_update' );
/* ---------- Dashboard ---------- */
function ysmcp_render_dashboard() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Permission denied.' );
}
$token = sanitize_text_field(
wp_unslash( $_GET['token'] ?? '' )
);
$data = $token ? get_transient( 'ysmcp_' . $token ) : false;
$index = $data ? ysmcp_index_pages() : [];
$rows = [];
$stats = [
'total' => 0,
'matched' => 0,
'missing' => 0,
'seo_diff' => 0,
'content_diff' => 0,
'identical' => 0,
];
if ( is_array( $data ) ) {
foreach ( $data['pages'] as $i => $source ) {
$stats['total']++;
$key = $source['post_type'] . '|' . $source['path'];
$post = $index[ $key ] ?? null;
$row = [
'i' => $i,
'source' => $source,
'post' => $post,
'status' => 'missing',
];
if ( $post instanceof WP_Post ) {
$destination = ysmcp_record( $post );
$diff = ysmcp_compare( $source, $destination );
$seo_count = ysmcp_seo_diff_count( $diff );
$content_diff = empty( $diff['content_text'] );
$row['destination'] = $destination;
$row['diff'] = $diff;
$row['seo_count'] = $seo_count;
$row['content_diff'] = $content_diff;
$row['status'] = $seo_count
? 'seo-diff'
: ( $content_diff ? 'content-diff' : 'identical' );
$stats['matched']++;
if ( $seo_count ) {
$stats['seo_diff']++;
}
if ( $content_diff ) {
$stats['content_diff']++;
}
if ( ! $seo_count && ! $content_diff ) {
$stats['identical']++;
}
} else {
$stats['missing']++;
}
$rows[] = $row;
}
}
?>
<div class="wrap ysmcp-wrap">
<style>
.ysmcp-wrap { max-width: 1600px; }
.ysmcp-hero {
background: linear-gradient(120deg,#172554,#3730a3);
color:#fff; padding:28px 30px; border-radius:12px;
margin:20px 0; display:flex; justify-content:space-between;
gap:20px; align-items:center;
}
.ysmcp-hero h1 { color:#fff; font-size:25px; margin:0 0 8px; }
.ysmcp-hero p { margin:0; color:#e0e7ff; }
.ysmcp-card-grid {
display:grid; grid-template-columns:repeat(5,minmax(130px,1fr));
gap:14px; margin:20px 0;
}
.ysmcp-card {
background:#fff; border:1px solid #e2e8f0; border-radius:10px;
padding:18px; box-shadow:0 1px 2px rgba(0,0,0,.03);
}
.ysmcp-card span { color:#64748b; display:block; font-size:12px; }
.ysmcp-card strong { display:block; font-size:26px; margin-top:7px; color:#172033; }
.ysmcp-panel {
background:#fff; border:1px solid #e2e8f0; border-radius:10px;
padding:20px; margin:18px 0;
}
.ysmcp-controls {
display:flex; flex-wrap:wrap; align-items:center; gap:10px;
margin:18px 0;
}
.ysmcp-controls input[type=search] { min-width:260px; }
.ysmcp-table { border:1px solid #e2e8f0; }
.ysmcp-table th { background:#f8fafc; }
.ysmcp-table td { vertical-align:top; padding:13px 10px; }
.ysmcp-page { font-weight:600; color:#172554; }
.ysmcp-muted { color:#64748b; font-size:12px; margin-top:4px; }
.ysmcp-badge {
display:inline-block; border-radius:20px; padding:4px 9px;
font-size:11px; font-weight:600; white-space:nowrap;
}
.ysmcp-green { background:#dcfce7; color:#166534; }
.ysmcp-amber { background:#fef3c7; color:#92400e; }
.ysmcp-red { background:#fee2e2; color:#991b1b; }
.ysmcp-blue { background:#dbeafe; color:#1d4ed8; }
.ysmcp-gray { background:#f1f5f9; color:#475569; }
.ysmcp-field { margin-bottom:12px; }
.ysmcp-field:last-child { margin-bottom:0; }
.ysmcp-field b { display:block; margin-bottom:4px; font-size:12px; }
.ysmcp-value {
background:#f8fafc; border:1px solid #e2e8f0; border-radius:5px;
padding:7px; overflow-wrap:anywhere; white-space:pre-wrap;
max-width:300px; font-size:12px;
}
.ysmcp-actions {
position:sticky; bottom:0; background:#fff; z-index:10;
padding:14px; border:1px solid #cbd5e1; border-radius:8px;
box-shadow:0 -3px 12px rgba(15,23,42,.08); margin-top:15px;
}
.ysmcp-empty { padding:28px; text-align:center; color:#64748b; }
@media(max-width:1000px) {
.ysmcp-card-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }
.ysmcp-hero { align-items:flex-start; flex-direction:column; }
}
</style>
<div class="ysmcp-hero">
<div>
<h1>SEO Migration Comparator</h1>
<p>Compare your original Elementor site with your new Bricks staging site.</p>
<p style="margin-top:8px;font-size:12px">
Source: <?php echo esc_html( $data['source_url'] ?? 'Not imported' ); ?>
</p>
</div>
<div>
<span class="ysmcp-badge ysmcp-blue">Yoast SEO</span>
<span class="ysmcp-badge ysmcp-green">Read-only comparison</span>
</div>
</div>
<?php
$notice = get_transient(
'ysmcp_result_' . get_current_user_id()
);
if ( is_array( $notice ) ) {
delete_transient(
'ysmcp_result_' . get_current_user_id()
);
echo '<div class="notice notice-success is-dismissible"><p>';
echo esc_html(
sprintf(
'Update completed. Processed %d pages; skipped %d.',
$notice['updated'],
$notice['skipped']
)
);
echo '</p></div>';
}
?>
<div class="ysmcp-panel">
<h2>Import source export</h2>
<p>Upload the JSON exported from your original Elementor site. The comparison does not change page content or design.</p>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data">
<input type="hidden" name="action" value="ysmcp_upload">
<?php wp_nonce_field( 'ysmcp_upload' ); ?>
<input type="file" name="ysmc_json" accept=".json,application/json" required>
<?php submit_button( 'Import and compare', 'primary', 'submit', false ); ?>
</form>
</div>
<?php if ( ! is_array( $data ) ) : ?>
<div class="ysmcp-panel ysmcp-empty">
<h2>No comparison loaded</h2>
<p>Import your source JSON to view the migration dashboard.</p>
</div>
<?php else : ?>
<div class="ysmcp-card-grid">
<?php
$cards = [
[ 'Total source pages', $stats['total'] ],
[ 'Matched pages', $stats['matched'] ],
[ 'SEO differences', $stats['seo_diff'] ],
[ 'Content differences', $stats['content_diff'] ],
[ 'Missing / ambiguous', $stats['missing'] ],
];
foreach ( $cards as $card ) :
?>
<div class="ysmcp-card">
<span><?php echo esc_html( $card[0] ); ?></span>
<strong><?php echo esc_html( number_format_i18n( $card[1] ) ); ?></strong>
</div>
<?php endforeach; ?>
</div>
<?php if ( ! ysmcp_is_staging() ) : ?>
<div class="notice notice-warning">
<p><strong>Read-only mode:</strong> this host is not recognized as staging or local development. Updates are disabled.</p>
</div>
<?php endif; ?>
<div class="ysmcp-panel">
<h2>Page comparison</h2>
<p>Choose pages with SEO differences, inspect the source and destination values, and select only the pages you want to update.</p>
<div class="ysmcp-controls">
<input type="search" id="ysmcp-search" placeholder="Search page title or URL…" aria-label="Search pages">
<select id="ysmcp-filter" aria-label="Filter comparison results">
<option value="all">All results</option>
<option value="seo-diff">SEO differences</option>
<option value="content-diff">Content differences</option>
<option value="identical">SEO and content match</option>
<option value="missing">Missing / ambiguous</option>
</select>
<button type="button" class="button" id="ysmcp-select-visible">Select visible matched pages</button>
<button type="button" class="button" id="ysmcp-clear">Clear selection</button>
<span id="ysmcp-visible-count" class="ysmcp-muted"></span>
</div>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="ysmcp-update-form">
<input type="hidden" name="action" value="ysmcp_update">
<input type="hidden" name="token" value="<?php echo esc_attr( $token ); ?>">
<?php wp_nonce_field( 'ysmcp_update' ); ?>
<input type="hidden" name="confirm" id="ysmcp-confirm" value="">
<div style="overflow-x:auto">
<table class="widefat striped ysmcp-table">
<thead>
<tr>
<th><input type="checkbox" id="ysmcp-select-all" aria-label="Select all visible matched pages"></th>
<th>Page</th>
<th>Status</th>
<th>SEO title</th>
<th>Meta description</th>
<th>Focus keyphrase</th>
<th>Content &amp; details</th>
</tr>
</thead>
<tbody id="ysmcp-rows">
<?php foreach ( $rows as $row ) :
$source = $row['source'];
$post = $row['post'];
$status = $row['status'];
$search_text = strtolower(
( $source['title'] ?? '' ) . ' ' .
( $source['path'] ?? '' )
);
$badge_class = [
'seo-diff' => 'ysmcp-amber',
'content-diff' => 'ysmcp-blue',
'identical' => 'ysmcp-green',
'missing' => 'ysmcp-red',
][ $status ];
$badge_text = [
'seo-diff' => 'SEO differs',
'content-diff' => 'Content differs',
'identical' => 'SEO & content match',
'missing' => 'Missing / ambiguous',
][ $status ];
?>
<tr
data-status="<?php echo esc_attr( $status ); ?>"
data-search="<?php echo esc_attr( $search_text ); ?>"
>
<td>
<?php if ( $post instanceof WP_Post ) : ?>
<input type="checkbox" class="ysmcp-row-check" name="selected[]" value="<?php echo esc_attr( $row['i'] ); ?>">
<?php endif; ?>
</td>
<td>
<div class="ysmcp-page"><?php echo esc_html( $source['title'] ?: '(Untitled)' ); ?></div>
<div class="ysmcp-muted"><?php echo esc_html( $source['path'] ); ?></div>
<?php if ( $post instanceof WP_Post ) : ?>
<div class="ysmcp-muted">Staging ID: <?php echo esc_html( $post->ID ); ?></div>
<?php endif; ?>
</td>
<td>
<span class="ysmcp-badge <?php echo esc_attr( $badge_class ); ?>"><?php echo esc_html( $badge_text ); ?></span>
</td>
<?php if ( $post instanceof WP_Post ) :
$destination = $row['destination'];
$diff = $row['diff'];
foreach ( [
'_yoast_wpseo_title' => 'SEO title',
'_yoast_wpseo_metadesc' => 'Meta description',
'_yoast_wpseo_focuskw' => 'Focus keyphrase',
] as $field => $label ) :
$source_value = (string) ( $source['seo'][ $field ] ?? '' );
$destination_value = (string) ( $destination['seo'][ $field ] ?? '' );
?>
<td>
<span class="ysmcp-badge <?php echo esc_attr( $diff[ $field ] ? 'ysmcp-green' : 'ysmcp-amber' ); ?>">
<?php echo esc_html( $diff[ $field ] ? 'Match' : 'Different' ); ?>
</span>
<details style="margin-top:8px">
<summary>Compare values</summary>
<div class="ysmcp-field">
<b>Source</b>
<div class="ysmcp-value"><?php echo esc_html( $source_value !== '' ? $source_value : '(empty)' ); ?></div>
</div>
<div class="ysmcp-field">
<b>Staging</b>
<div class="ysmcp-value"><?php echo esc_html( $destination_value !== '' ? $destination_value : '(empty)' ); ?></div>
</div>
</details>
</td>
<?php endforeach; ?>
<td>
<div class="ysmcp-field">
<b>Main content</b>
<span class="ysmcp-badge <?php echo esc_attr( $diff['content_text'] ? 'ysmcp-green' : 'ysmcp-blue' ); ?>">
<?php echo esc_html( $diff['content_text'] ? 'Text match' : 'Text differs' ); ?>
</span>
</div>
<details>
<summary>Other page details</summary>
<?php foreach ( [
'title' => 'Page title',
'parent_path' => 'Parent path',
'status' => 'Status',
'excerpt' => 'Excerpt',
'template' => 'Template',
'featured_image' => 'Featured image',
] as $field => $label ) : ?>
<div class="ysmcp-field">
<b><?php echo esc_html( $label ); ?></b>
<span class="ysmcp-badge <?php echo esc_attr( $diff[ $field ] ? 'ysmcp-green' : 'ysmcp-amber' ); ?>">
<?php echo esc_html( $diff[ $field ] ? 'Match' : 'Different' ); ?>
</span>
<?php if ( in_array( $field, [ 'title', 'featured_image' ], true ) ) : ?>
<div class="ysmcp-muted">Source: <?php echo esc_html( $source[ $field ] ?? '' ); ?></div>
<div class="ysmcp-muted">Staging: <?php echo esc_html( $destination[ $field ] ?? '' ); ?></div>
<?php endif; ?>
</div>
<?php endforeach; ?>
</details>
</td>
<?php else : ?>
<td colspan="4">
<span class="ysmcp-badge ysmcp-red">No safe match</span>
<p class="ysmcp-muted">This page will not be updated.</p>
</td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="ysmcp-actions">
<p><strong>Update scope:</strong> SEO title, meta description and focus keyphrase only. Empty source fields are skipped. Page content, Bricks layouts and other metadata will not be imported.</p>
<?php if ( ysmcp_is_staging() ) : ?>
<label>
<input type="checkbox" id="ysmcp-approval" required>
I have reviewed my selections and authorize these SEO metadata updates.
</label>
<p style="margin-bottom:0">
<button type="submit" class="button button-primary button-hero" id="ysmcp-submit">Confirm selected updates</button>
</p>
<?php else : ?>
<strong>Updates disabled on this host.</strong>
<?php endif; ?>
</div>
</form>
</div>
<script>
(function () {
const search = document.getElementById('ysmcp-search');
const filter = document.getElementById('ysmcp-filter');
const rows = Array.from(document.querySelectorAll('#ysmcp-rows tr'));
const selectAll = document.getElementById('ysmcp-select-all');
const selectVisible = document.getElementById('ysmcp-select-visible');
const clear = document.getElementById('ysmcp-clear');
const count = document.getElementById('ysmcp-visible-count');
const form = document.getElementById('ysmcp-update-form');
function applyFilters() {
const term = search.value.toLowerCase().trim();
const selectedFilter = filter.value;
let visible = 0;
rows.forEach(function (row) {
const matchesText = (row.dataset.search || '').includes(term);
const matchesFilter = selectedFilter === 'all'
|| row.dataset.status === selectedFilter;
const show = matchesText && matchesFilter;
row.hidden = !show;
if (show) visible++;
});
count.textContent = visible + ' visible pages';
selectAll.checked = false;
}
search.addEventListener('input', applyFilters);
filter.addEventListener('change', applyFilters);
selectAll.addEventListener('change', function () {
rows.forEach(function (row) {
if (row.hidden) return;
const checkbox = row.querySelector('.ysmcp-row-check');
if (checkbox) checkbox.checked = selectAll.checked;
});
});
selectVisible.addEventListener('click', function () {
rows.forEach(function (row) {
if (row.hidden) return;
const checkbox = row.querySelector('.ysmcp-row-check');
if (checkbox) checkbox.checked = true;
});
});
clear.addEventListener('click', function () {
document.querySelectorAll('.ysmcp-row-check').forEach(function (checkbox) {
checkbox.checked = false;
});
selectAll.checked = false;
});
form.addEventListener('submit', function (event) {
const selected = document.querySelectorAll('.ysmcp-row-check:checked');
if (!selected.length) {
event.preventDefault();
alert('Select at least one matched page.');
return;
}
if (!document.getElementById('ysmcp-approval').checked) {
event.preventDefault();
alert('Please confirm that you reviewed the selections.');
return;
}
if (!confirm(
'Update ' + selected.length +
' selected page(s)? Only the three approved Yoast fields will be changed.'
)) {
event.preventDefault();
return;
}
document.getElementById('ysmcp-confirm').value = 'yes';
});
applyFilters();
})();
</script>
<?php endif; ?>
</div>
<?php
}
/**
* Yoast Migration Comparator - Source Export
* Read-only export. Does not update posts or metadata.
*/
add_action('admin_menu', function () {
add_management_page(
'Yoast Migration Export',
'Yoast Migration Export',
'manage_options',
'ysmc-source-export',
'ysmc_source_export_screen'
);
});
function ysmc_source_text($data, &$out = []) {
if (!is_array($data)) {
return $out;
}
$keys = [
'title', 'heading', 'text', 'editor',
'text_editor', 'content', 'description',
'button_text', 'label'
];
foreach ($data as $key => $value) {
if (is_string($value) && in_array((string) $key, $keys, true)) {
$text = trim(preg_replace(
'/\s+/u',
' ',
html_entity_decode(
wp_strip_all_tags($value),
ENT_QUOTES | ENT_HTML5,
'UTF-8'
)
));
if ($text !== '') {
$out[] = $text;
}
} elseif (is_array($value)) {
ysmc_source_text($value, $out);
}
}
return $out;
}
function ysmc_source_page_record($post) {
$elementor = get_post_meta($post->ID, '_elementor_data', true);
if (is_string($elementor)) {
$elementor = json_decode($elementor, true);
}
$texts = [];
if (is_array($elementor)) {
ysmc_source_text($elementor, $texts);
}
$content = trim(preg_replace(
'/\s+/u',
' ',
wp_strip_all_tags($post->post_content)
));
if ($content !== '') {
$texts[] = $content;
}
$texts = array_values(array_unique($texts));
$parent = $post->post_parent ? get_post($post->post_parent) : null;
$image_id = get_post_thumbnail_id($post->ID);
$image_file = $image_id
? get_post_meta($image_id, '_wp_attached_file', true)
: '';
return [
'post_type' => $post->post_type,
'slug' => $post->post_name,
'path' => get_page_uri($post),
'parent_path' => $parent ? get_page_uri($parent) : '',
'title' => $post->post_title,
'status' => $post->post_status,
'excerpt' => $post->post_excerpt,
'template' => (string) get_post_meta(
$post->ID, '_wp_page_template', true
),
'featured_image' => $image_file ? basename($image_file) : '',
'content_text' => implode(' | ', $texts),
'seo' => [
'_yoast_wpseo_title' => (string) get_post_meta(
$post->ID, '_yoast_wpseo_title', true
),
'_yoast_wpseo_metadesc' => (string) get_post_meta(
$post->ID, '_yoast_wpseo_metadesc', true
),
'_yoast_wpseo_focuskw' => (string) get_post_meta(
$post->ID, '_yoast_wpseo_focuskw', true
),
],
];
}
function ysmc_source_export_screen() {
if (!current_user_can('manage_options')) {
wp_die('Permission denied.');
}
echo '<div class="wrap"><h1>Yoast Migration Export</h1>';
echo '<p>Export page details and Yoast metadata. This operation is read-only.</p>';
echo '<form method="post" action="' .
esc_url(admin_url('admin-post.php')) . '">';
echo '<input type="hidden" name="action" value="ysmc_source_download">';
wp_nonce_field('ysmc_source_download');
submit_button('Download JSON export');
echo '</form></div>';
}
add_action('admin_post_ysmc_source_download', function () {
if (!current_user_can('manage_options')) {
wp_die('Permission denied.');
}
check_admin_referer('ysmc_source_download');
$posts = get_posts([
'post_type' => 'page',
'post_status' => [
'publish', 'draft', 'private', 'pending', 'future'
],
'posts_per_page' => -1,
'orderby' => 'ID',
'order' => 'ASC',
]);
$pages = [];
foreach ($posts as $post) {
$pages[] = ysmc_source_page_record($post);
}
$payload = [
'format' => 'ysmc-export',
'version' => 1,
'source_url' => home_url(),
'generated_at' => gmdate('c'),
'pages' => $pages,
];
nocache_headers();
header('Content-Type: application/json; charset=utf-8');
header('Content-Disposition: attachment; filename="yoast-migration-export.json"');
echo wp_json_encode(
$payload,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);
exit;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment