Home / Admin / WpPages_DIR_AD_SYNC – WordPress Pages Sync Engine
Duplicate Snippet

Embed Snippet on Your Site

WpPages_DIR_AD_SYNC – WordPress Pages Sync Engine

Description: Comprehensive sync functionality for pages with full content analysis
* Location: Run Everywhere
* Priority: 20

ismail daugherty PRO
<10
Code Preview
php
<?php
/**
 * WPCode Snippet: WordPress Pages Sync Engine
 * Description: Comprehensive sync functionality for pages with full content analysis
 * Location: Run Everywhere
 * Priority: 20
 * 
 * FEATURES:
 * - Manual sync via admin bar button
 * - Auto-sync on page save/update
 * - Orphaned post cleanup
 * - RankMath SEO extraction
 * - Block analysis (GravityView, Gravity Forms, LifterLMS, iFrames, HTML)
 * - WP Fusion protection detection
 * - Shortcode extraction
 * - Theme settings capture
 * - Custom taxonomy extraction
 * - Full metadata capture (URLs, dates, author, visibility)
 */
defined( 'ABSPATH' ) || exit;
// ==========================================
// ADMIN BAR SYNC BUTTON
// ==========================================
add_action( 'admin_bar_menu', function( $wp_admin_bar ) {
    if ( ! current_user_can( 'manage_options' ) ) return;
    
    $wp_admin_bar->add_node( [
        'id'    => 'wp-pages-sync-test',
        'title' => '🔄 Sync WP Pages',
        'href'  => admin_url( 'admin.php?wp_pages_sync_test=1' ),
    ] );
}, 999 );
// ==========================================
// MANUAL SYNC TRIGGER
// ==========================================
add_action( 'admin_init', function() {
    if ( ! isset( $_GET['wp_pages_sync_test'] ) || ! current_user_can( 'manage_options' ) ) return;
    
    // First, clean up orphaned posts
    wp_pages_cleanup_orphaned_posts();
    
    // Then sync all existing pages
    $pages = get_posts( [
        'post_type'      => 'page',
        'post_status'    => 'any',
        'posts_per_page' => -1,
        'orderby'        => 'ID',
        'order'          => 'ASC',
    ] );
    
    $count = 0;
    
    foreach ( $pages as $page ) {
        wp_pages_mirror_page_to_cpt( $page );
        $count++;
    }
    
    wp_redirect( admin_url( 'edit.php?post_type=wp_pages_sync&synced=' . $count ) );
    exit;
} );
// ==========================================
// SUCCESS MESSAGE
// ==========================================
add_action( 'admin_notices', function() {
    if ( isset( $_GET['synced'] ) && $_GET['post_type'] === 'wp_pages_sync' ) {
        $count = intval( $_GET['synced'] );
        echo '<div class="notice notice-success"><p>✅ Synced ' . $count . ' pages to CPT!</p></div>';
    }
} );
// ==========================================
// CLEANUP ORPHANED POSTS
// ==========================================
function wp_pages_cleanup_orphaned_posts() {
    // Get all actual page IDs
    $actual_pages = get_posts( [
        'post_type'      => 'page',
        'post_status'    => 'any',
        'posts_per_page' => -1,
        'fields'         => 'ids',
    ] );
    
    error_log( 'WP_PAGES_SYNC: Active page IDs: ' . implode( ', ', $actual_pages ) );
    
    // Query all sync posts
    $all_sync_posts = new WP_Query( [
        'post_type'      => 'wp_pages_sync',
        'posts_per_page' => -1,
        'fields'         => 'ids',
    ] );
    
    $deleted_count = 0;
    
    foreach ( $all_sync_posts->posts as $sync_post_id ) {
        $page_id = intval( get_post_meta( $sync_post_id, 'page_id', true ) );
        
        // If this sync post is for a page that no longer exists, delete it
        if ( $page_id && ! in_array( $page_id, $actual_pages, true ) ) {
            wp_delete_post( $sync_post_id, true );
            $deleted_count++;
            error_log( "WP_PAGES_SYNC: Deleted orphaned sync post for non-existent page {$page_id} (post {$sync_post_id})" );
        }
    }
    
    if ( $deleted_count > 0 ) {
        error_log( "WP_PAGES_SYNC: Cleaned up {$deleted_count} orphaned sync posts" );
    }
}
// ==========================================
// MAIN SYNC FUNCTION
// ==========================================
function wp_pages_mirror_page_to_cpt( $page ) {
    // Verify CPT exists
    if ( ! post_type_exists( 'wp_pages_sync' ) ) {
        error_log( 'WP_PAGES_SYNC: CPT wp_pages_sync does not exist!' );
        return;
    }
    
    // Validate page data
    if ( empty( $page ) || ! is_object( $page ) ) {
        error_log( 'WP_PAGES_SYNC: Invalid page data' );
        return;
    }
    
    $page_id = absint( $page->ID );
    $page_title = ! empty( $page->post_title ) ? sanitize_text_field( $page->post_title ) : 'Page ' . $page_id;
    
    error_log( "WP_PAGES_SYNC: Processing page {$page_id} - {$page_title}" );
    
    // Get existing sync post for this page
    $existing_query = new WP_Query( [
        'post_type'      => 'wp_pages_sync',
        'posts_per_page' => 1,
        'fields'         => 'ids',
        'meta_query'     => [
            [
                'key'   => 'page_id',
                'value' => $page_id,
            ]
        ]
    ] );
    
    $existing_post_id = ! empty( $existing_query->posts ) ? $existing_query->posts[0] : false;
    
    // Prepare post data
    $slug = sanitize_title( "wp-page-{$page_id}" );
    
    $post_data = [
        'post_type'   => 'wp_pages_sync',
        'post_status' => 'publish',
        'post_title'  => $page_title,
        'post_name'   => $slug,
        'post_parent' => 0, // Flat structure for sync CPT
    ];
    
    // Build comprehensive meta data
    $meta_data = wp_pages_build_meta_data( $page );
    
    if ( $existing_post_id ) {
        // Update existing
        $post_data['ID'] = $existing_post_id;
        $post_id = wp_update_post( $post_data );
        error_log( "WP_PAGES_SYNC: Updated page {$page_id} (sync post {$post_id})" );
    } else {
        // Create new
        $post_id = wp_insert_post( $post_data );
        error_log( "WP_PAGES_SYNC: Created page {$page_id} (sync post {$post_id})" );
    }
    
    // Update all meta
    if ( $post_id && ! is_wp_error( $post_id ) ) {
        foreach ( $meta_data as $key => $value ) {
            update_post_meta( $post_id, $key, $value );
        }
        
        // Add ACF field key references for URL fields
        update_post_meta( $post_id, '_wp_page_edit_link', 'field_wp_page_edit_link' );
        update_post_meta( $post_id, '_wp_page_view_link', 'field_wp_page_view_link' );
        update_post_meta( $post_id, '_page_url', 'field_wp_page_url' );
        
        error_log( "WP_PAGES_SYNC: Completed page {$page_id}" );
    }
}
// ==========================================
// BUILD COMPREHENSIVE META DATA
// ==========================================
function wp_pages_build_meta_data( $page ) {
    $page_id = $page->ID;
    
    // Get page author data
    $author = get_userdata( $page->post_author );
    $author_role = ! empty( $author->roles ) ? implode( ', ', $author->roles ) : '';
    
    // Get featured image
    $featured_image_id = get_post_thumbnail_id( $page_id );
    $featured_image_url = $featured_image_id ? wp_get_attachment_url( $featured_image_id ) : '';
    
    // Get page visibility
    $visibility = 'public';
    if ( $page->post_status === 'private' ) {
        $visibility = 'private';
    } elseif ( ! empty( $page->post_password ) ) {
        $visibility = 'password';
    }
    
    // Parse page content for blocks
    $content_analysis = wp_pages_analyze_content( $page->post_content, $page_id );
    
    // Get RankMath SEO data
    $seo_data = wp_pages_get_rankmath_data( $page_id );
    
    // Get theme settings
    $theme_settings = wp_pages_get_theme_settings( $page_id );
    
    // Get custom taxonomies
    $custom_taxonomies = wp_pages_get_custom_taxonomies( $page_id );
    
    // Build meta array
    $meta = [
        // Quick Access Links
        'wp_page_edit_link' => admin_url( 'post.php?post=' . $page_id . '&action=edit' ),
        'wp_page_view_link' => get_permalink( $page_id ),
        
        // URLs & Permalinks - CRITICAL
        'page_url'          => get_permalink( $page_id ),
        'page_slug'         => $page->post_name,
        
        // Basic Page Info
        'page_id'           => $page_id,
        'page_status'       => $page->post_status,
        'page_template'     => get_page_template_slug( $page_id ) ?: 'default',
        'page_parent_id'    => $page->post_parent,
        'page_order'        => $page->menu_order,
        
        // Author Information
        'page_author_id'    => $page->post_author,
        'page_author_name'  => $author ? $author->display_name : '',
        'page_author_email' => $author ? $author->user_email : '',
        'page_author_role'  => $author_role,
        
        // Date/Time Information
        'page_date_created'   => $page->post_date,
        'page_date_modified'  => $page->post_modified,
        'page_date_published' => ( $page->post_status === 'publish' ) ? $page->post_date : '',
        
        // Access & Visibility
        'page_visibility'   => $visibility,
        'page_password'     => $page->post_password,
        'comment_status'    => $page->comment_status,
        
        // Block Counts
        'blocks_count'               => $content_analysis['blocks_count'],
        'gravityview_blocks_count'   => $content_analysis['gravityview_count'],
        'gravity_forms_blocks_count' => $content_analysis['gravity_forms_count'],
        'lifterlms_blocks_count'     => $content_analysis['lifterlms_count'],
        'iframes_count'              => $content_analysis['iframes_count'],
        'shortcodes_count'           => $content_analysis['shortcodes_count'],
        'html_blocks_count'          => $content_analysis['html_blocks_count'],
        
        // Featured Image
        'featured_image_url' => $featured_image_url,
        'featured_image_id'  => $featured_image_id,
        
        // Custom Taxonomies
        'custom_taxonomies' => $custom_taxonomies,
        
        // Theme Settings
        'theme_settings' => $theme_settings,
        
        // Last Sync
        'last_sync' => current_time( 'mysql' ),
        
        // RankMath SEO Data
        'seo_enabled'        => $seo_data['enabled'],
        'seo_title'          => $seo_data['title'],
        'seo_description'    => $seo_data['description'],
        'seo_focus_keyword'  => $seo_data['focus_keyword'],
        'seo_score'          => $seo_data['score'],
        'seo_canonical_url'  => $seo_data['canonical'],
        'og_title'           => $seo_data['og_title'],
        'og_description'     => $seo_data['og_description'],
        'og_image_url'       => $seo_data['og_image'],
        'seo_robots'         => $seo_data['robots'],
        'seo_schema_type'    => $seo_data['schema_type'],
        'seo_complete_data'  => $seo_data['complete_data'],
        
        // GravityView Blocks
        'has_gravityview_blocks'  => $content_analysis['has_gravityview'],
        'gravityview_blocks_details' => $content_analysis['gravityview_details'],
        
        // Gravity Forms Blocks
        'has_gravity_forms_blocks' => $content_analysis['has_gravity_forms'],
        'gravity_forms_blocks_details' => $content_analysis['gravity_forms_details'],
        
        // LifterLMS Blocks
        'has_lifterlms_blocks' => $content_analysis['has_lifterlms'],
        'lifterlms_blocks_details' => $content_analysis['lifterlms_details'],
        
        // iFrames & Embeds
        'has_iframes' => $content_analysis['has_iframes'],
        'iframes_details' => $content_analysis['iframes_details'],
        
        // WP Fusion Protection
        'wp_fusion_protected' => $content_analysis['wp_fusion_protected'],
        'wp_fusion_tags_count' => $content_analysis['wp_fusion_tags_count'],
        'wp_fusion_details' => $content_analysis['wp_fusion_details'],
        
        // Shortcodes
        'has_shortcodes' => $content_analysis['has_shortcodes'],
        'shortcodes_details' => $content_analysis['shortcodes_details'],
        
        // HTML Blocks
        'has_html_blocks' => $content_analysis['has_html_blocks'],
        'html_blocks_details' => $content_analysis['html_blocks_details'],
        
        // Block Analysis
        'block_analysis' => $content_analysis['block_analysis'],
        
        // Page Content
        'page_content' => $page->post_content,
        'page_excerpt' => $page->post_excerpt,
    ];
    
    return $meta;
}
// ==========================================
// CONTENT ANALYSIS FUNCTION
// ==========================================
function wp_pages_analyze_content( $content, $page_id ) {
    $analysis = [
        'blocks_count'      => 0,
        'gravityview_count' => 0,
        'gravity_forms_count' => 0,
        'lifterlms_count' => 0,
        'iframes_count' => 0,
        'shortcodes_count' => 0,
        'html_blocks_count' => 0,
        
        'has_gravityview' => false,
        'gravityview_details' => '',
        
        'has_gravity_forms' => false,
        'gravity_forms_details' => '',
        
        'has_lifterlms' => false,
        'lifterlms_details' => '',
        
        'has_iframes' => false,
        'iframes_details' => '',
        
        'wp_fusion_protected' => false,
        'wp_fusion_tags_count' => 0,
        'wp_fusion_details' => '',
        
        'has_shortcodes' => false,
        'shortcodes_details' => '',
        
        'has_html_blocks' => false,
        'html_blocks_details' => '',
        
        'block_analysis' => '',
    ];
    
    // Parse Gutenberg blocks
    if ( function_exists( 'parse_blocks' ) ) {
        $blocks = parse_blocks( $content );
        $analysis['blocks_count'] = count( $blocks );
        
        // Analyze each block
        $block_details = [];
        $gravityview_blocks = [];
        $gravity_forms_blocks = [];
        $lifterlms_blocks = [];
        $html_blocks = [];
        $iframe_blocks = [];
        
        foreach ( $blocks as $block ) {
            if ( empty( $block['blockName'] ) ) continue;
            
            // GravityView blocks
            if ( strpos( $block['blockName'], 'gravityview' ) !== false ) {
                $analysis['gravityview_count']++;
                $analysis['has_gravityview'] = true;
                $gravityview_blocks[] = wp_pages_format_gravityview_block( $block );
            }
            
            // Gravity Forms blocks
            if ( strpos( $block['blockName'], 'gravityforms' ) !== false ) {
                $analysis['gravity_forms_count']++;
                $analysis['has_gravity_forms'] = true;
                $gravity_forms_blocks[] = wp_pages_format_gravity_forms_block( $block );
            }
            
            // LifterLMS blocks
            if ( strpos( $block['blockName'], 'llms' ) !== false || strpos( $block['blockName'], 'lifterlms' ) !== false ) {
                $analysis['lifterlms_count']++;
                $analysis['has_lifterlms'] = true;
                $lifterlms_blocks[] = wp_pages_format_lifterlms_block( $block );
            }
            
            // HTML blocks
            if ( $block['blockName'] === 'core/html' || $block['blockName'] === 'core/freeform' ) {
                $analysis['html_blocks_count']++;
                $analysis['has_html_blocks'] = true;
                $html_blocks[] = $block['innerHTML'];
            }
            
            // Check for iframes in any block
            if ( ! empty( $block['innerHTML'] ) && strpos( $block['innerHTML'], '<iframe' ) !== false ) {
                $analysis['iframes_count']++;
                $analysis['has_iframes'] = true;
                $iframe_blocks[] = wp_pages_extract_iframes( $block['innerHTML'] );
            }
            
            $block_details[] = wp_pages_format_block_details( $block );
        }
        
        // Format details
        $analysis['gravityview_details'] = ! empty( $gravityview_blocks ) ? implode( "\n\n", $gravityview_blocks ) : 'No GravityView blocks detected.';
        $analysis['gravity_forms_details'] = ! empty( $gravity_forms_blocks ) ? implode( "\n\n", $gravity_forms_blocks ) : 'No Gravity Forms blocks detected.';
        $analysis['lifterlms_details'] = ! empty( $lifterlms_blocks ) ? implode( "\n\n", $lifterlms_blocks ) : 'No LifterLMS blocks detected.';
        $analysis['html_blocks_details'] = ! empty( $html_blocks ) ? implode( "\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n", $html_blocks ) : 'No HTML blocks detected.';
        $analysis['iframes_details'] = ! empty( $iframe_blocks ) ? implode( "\n\n", array_filter( $iframe_blocks ) ) : 'No iframes detected.';
        $analysis['block_analysis'] = ! empty( $block_details ) ? implode( "\n\n", $block_details ) : 'No blocks detected.';
    }
    
    // Detect shortcodes
    $shortcode_analysis = wp_pages_detect_shortcodes( $content );
    $analysis['has_shortcodes'] = $shortcode_analysis['has_shortcodes'];
    $analysis['shortcodes_count'] = $shortcode_analysis['count'];
    $analysis['shortcodes_details'] = $shortcode_analysis['details'];
    
    // Detect WP Fusion protection
    $wp_fusion_data = wp_pages_detect_wp_fusion( $page_id, $content );
    $analysis['wp_fusion_protected'] = $wp_fusion_data['protected'];
    $analysis['wp_fusion_tags_count'] = $wp_fusion_data['tags_count'];
    $analysis['wp_fusion_details'] = $wp_fusion_data['details'];
    
    return $analysis;
}
// ==========================================
// FORMAT GRAVITYVIEW BLOCK
// ==========================================
function wp_pages_format_gravityview_block( $block ) {
    $output = [];
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "GRAVITYVIEW BLOCK";
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "";
    $output[] = "Block Type: " . $block['blockName'];
    
    if ( ! empty( $block['attrs'] ) ) {
        $output[] = "";
        $output[] = "ATTRIBUTES:";
        foreach ( $block['attrs'] as $key => $value ) {
            if ( is_array( $value ) || is_object( $value ) ) {
                $output[] = "  {$key}: " . print_r( $value, true );
            } else {
                $output[] = "  {$key}: {$value}";
            }
        }
    }
    
    if ( ! empty( $block['innerHTML'] ) ) {
        $output[] = "";
        $output[] = "HTML OUTPUT:";
        $output[] = strip_tags( $block['innerHTML'] );
    }
    
    return implode( "\n", $output );
}
// ==========================================
// FORMAT GRAVITY FORMS BLOCK
// ==========================================
function wp_pages_format_gravity_forms_block( $block ) {
    $output = [];
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "GRAVITY FORMS BLOCK";
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "";
    $output[] = "Block Type: " . $block['blockName'];
    
    if ( ! empty( $block['attrs']['formId'] ) ) {
        $output[] = "Form ID: " . $block['attrs']['formId'];
    }
    
    if ( ! empty( $block['attrs'] ) ) {
        $output[] = "";
        $output[] = "SETTINGS:";
        foreach ( $block['attrs'] as $key => $value ) {
            if ( is_array( $value ) || is_object( $value ) ) {
                $output[] = "  {$key}: " . print_r( $value, true );
            } else {
                $output[] = "  {$key}: {$value}";
            }
        }
    }
    
    return implode( "\n", $output );
}
// ==========================================
// FORMAT LIFTERLMS BLOCK
// ==========================================
function wp_pages_format_lifterlms_block( $block ) {
    $output = [];
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "LIFTERLMS BLOCK";
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "";
    $output[] = "Block Type: " . $block['blockName'];
    
    if ( ! empty( $block['attrs'] ) ) {
        $output[] = "";
        $output[] = "ATTRIBUTES:";
        foreach ( $block['attrs'] as $key => $value ) {
            if ( is_array( $value ) || is_object( $value ) ) {
                $output[] = "  {$key}: " . print_r( $value, true );
            } else {
                $output[] = "  {$key}: {$value}";
            }
        }
    }
    
    return implode( "\n", $output );
}
// ==========================================
// EXTRACT IFRAMES
// ==========================================
function wp_pages_extract_iframes( $html ) {
    if ( empty( $html ) ) return '';
    
    preg_match_all( '/<iframe[^>]*>(.*?)<\/iframe>/is', $html, $matches );
    
    if ( empty( $matches[0] ) ) return '';
    
    $output = [];
    
    foreach ( $matches[0] as $index => $iframe ) {
        $output[] = "═══════════════════════════════════════════════";
        $output[] = "IFRAME #" . ( $index + 1 );
        $output[] = "═══════════════════════════════════════════════";
        
        // Extract src
        if ( preg_match( '/src=["\']([^"\']+)["\']/i', $iframe, $src_match ) ) {
            $src = $src_match[1];
            $output[] = "Source: " . $src;
            
            // Detect Google embeds
            if ( strpos( $src, 'docs.google.com' ) !== false ) {
                $output[] = "Type: Google Docs";
            } elseif ( strpos( $src, 'drive.google.com' ) !== false ) {
                $output[] = "Type: Google Drive";
            } elseif ( strpos( $src, 'forms.google.com' ) !== false || strpos( $src, 'docs.google.com/forms' ) !== false ) {
                $output[] = "Type: Google Forms";
            }
        }
        
        // Extract dimensions
        if ( preg_match( '/width=["\']([^"\']+)["\']/i', $iframe, $width_match ) ) {
            $output[] = "Width: " . $width_match[1];
        }
        if ( preg_match( '/height=["\']([^"\']+)["\']/i', $iframe, $height_match ) ) {
            $output[] = "Height: " . $height_match[1];
        }
        
        $output[] = "";
        $output[] = "Full HTML:";
        $output[] = $iframe;
        $output[] = "";
    }
    
    return implode( "\n", $output );
}
// ==========================================
// DETECT SHORTCODES
// ==========================================
function wp_pages_detect_shortcodes( $content ) {
    global $shortcode_tags;
    
    $result = [
        'has_shortcodes' => false,
        'count' => 0,
        'details' => '',
    ];
    
    if ( empty( $content ) ) {
        return $result;
    }
    
    // Find all shortcodes
    preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER );
    
    if ( empty( $matches ) ) {
        $result['details'] = 'No shortcodes detected.';
        return $result;
    }
    
    $result['has_shortcodes'] = true;
    $result['count'] = count( $matches );
    
    $shortcode_list = [];
    $shortcode_counts = [];
    
    foreach ( $matches as $match ) {
        $shortcode_name = $match[2];
        
        if ( ! isset( $shortcode_counts[ $shortcode_name ] ) ) {
            $shortcode_counts[ $shortcode_name ] = 0;
        }
        $shortcode_counts[ $shortcode_name ]++;
        
        $shortcode_list[] = [
            'name' => $shortcode_name,
            'full' => $match[0],
            'atts' => ! empty( $match[3] ) ? $match[3] : '',
        ];
    }
    
    $output = [];
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "SHORTCODES DETECTED: " . $result['count'];
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "";
    $output[] = "SUMMARY:";
    foreach ( $shortcode_counts as $name => $count ) {
        $output[] = "  [{$name}] - Used {$count} time(s)";
    }
    $output[] = "";
    $output[] = "DETAILED LIST:";
    $output[] = "";
    
    foreach ( $shortcode_list as $index => $sc ) {
        $output[] = "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━";
        $output[] = "SHORTCODE #" . ( $index + 1 );
        $output[] = "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━";
        $output[] = "Name: [{$sc['name']}]";
        if ( ! empty( $sc['atts'] ) ) {
            $output[] = "Attributes: " . trim( $sc['atts'] );
        }
        $output[] = "Full Shortcode: " . $sc['full'];
        $output[] = "";
    }
    
    $result['details'] = implode( "\n", $output );
    
    return $result;
}
// ==========================================
// DETECT WP FUSION PROTECTION
// ==========================================
function wp_pages_detect_wp_fusion( $page_id, $content ) {
    $result = [
        'protected' => false,
        'tags_count' => 0,
        'details' => 'No WP Fusion protection detected.',
    ];
    
    // Check if WP Fusion is active
    if ( ! function_exists( 'wp_fusion' ) ) {
        return $result;
    }
    
    $output = [];
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "WP FUSION PROTECTION STATUS";
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "";
    
    // Get page-level protection
    $wpf_settings = get_post_meta( $page_id, 'wpf-settings', true );
    
    if ( ! empty( $wpf_settings ) && ! empty( $wpf_settings['lock_content'] ) ) {
        $result['protected'] = true;
        
        $output[] = "🔒 PAGE-LEVEL PROTECTION: ENABLED";
        $output[] = "";
        
        if ( ! empty( $wpf_settings['allow_tags'] ) ) {
            $tags = $wpf_settings['allow_tags'];
            $result['tags_count'] = count( $tags );
            $output[] = "Required Tags: " . implode( ', ', $tags );
        }
        
        if ( ! empty( $wpf_settings['redirect'] ) ) {
            $output[] = "Redirect URL: " . $wpf_settings['redirect'];
        }
        
        $output[] = "";
    } else {
        $output[] = "PAGE-LEVEL PROTECTION: Not enabled";
        $output[] = "";
    }
    
    // Check for block-level protection (would need to parse blocks)
    // This is a simplified check
    if ( strpos( $content, 'wpf-' ) !== false || strpos( $content, 'wp-fusion' ) !== false ) {
        $output[] = "⚠️ Possible block-level WP Fusion protection detected in content.";
    }
    
    $result['details'] = implode( "\n", $output );
    
    return $result;
}
// ==========================================
// FORMAT BLOCK DETAILS
// ==========================================
function wp_pages_format_block_details( $block, $level = 0 ) {
    $indent = str_repeat( '  ', $level );
    $output = [];
    
    if ( empty( $block['blockName'] ) ) {
        return '';
    }
    
    $output[] = $indent . "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━";
    $output[] = $indent . "BLOCK: " . $block['blockName'];
    $output[] = $indent . "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━";
    
    if ( ! empty( $block['attrs'] ) ) {
        $output[] = $indent . "Attributes: " . print_r( $block['attrs'], true );
    }
    
    if ( ! empty( $block['innerBlocks'] ) ) {
        $output[] = $indent . "Inner Blocks: " . count( $block['innerBlocks'] );
        foreach ( $block['innerBlocks'] as $inner_block ) {
            $output[] = wp_pages_format_block_details( $inner_block, $level + 1 );
        }
    }
    
    $output[] = "";
    
    return implode( "\n", $output );
}
// ==========================================
// GET RANKMATH SEO DATA
// ==========================================
function wp_pages_get_rankmath_data( $page_id ) {
    $seo = [
        'enabled' => false,
        'title' => '',
        'description' => '',
        'focus_keyword' => '',
        'score' => '',
        'canonical' => '',
        'og_title' => '',
        'og_description' => '',
        'og_image' => '',
        'robots' => '',
        'schema_type' => '',
        'complete_data' => 'RankMath not configured or not active.',
    ];
    
    // Check if RankMath is active
    if ( ! class_exists( 'RankMath' ) ) {
        return $seo;
    }
    
    $seo['enabled'] = true;
    
    // Get RankMath meta
    $seo['title'] = get_post_meta( $page_id, 'rank_math_title', true );
    $seo['description'] = get_post_meta( $page_id, 'rank_math_description', true );
    $seo['focus_keyword'] = get_post_meta( $page_id, 'rank_math_focus_keyword', true );
    $seo['canonical'] = get_post_meta( $page_id, 'rank_math_canonical_url', true );
    
    // Open Graph
    $seo['og_title'] = get_post_meta( $page_id, 'rank_math_facebook_title', true );
    $seo['og_description'] = get_post_meta( $page_id, 'rank_math_facebook_description', true );
    $seo['og_image'] = get_post_meta( $page_id, 'rank_math_facebook_image', true );
    
    // Robots
    $robots_meta = get_post_meta( $page_id, 'rank_math_robots', true );
    if ( is_array( $robots_meta ) ) {
        $seo['robots'] = implode( ', ', $robots_meta );
    }
    
    // Schema
    $seo['schema_type'] = get_post_meta( $page_id, 'rank_math_rich_snippet', true );
    
    // SEO Score
    $seo['score'] = get_post_meta( $page_id, 'rank_math_seo_score', true );
    
    // Format complete data
    $output = [];
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "RANKMATH SEO DATA";
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "";
    $output[] = "SEO Title: " . ( $seo['title'] ?: '(Not set)' );
    $output[] = "Meta Description: " . ( $seo['description'] ?: '(Not set)' );
    $output[] = "Focus Keyword: " . ( $seo['focus_keyword'] ?: '(Not set)' );
    $output[] = "SEO Score: " . ( $seo['score'] ?: 'N/A' );
    $output[] = "Canonical URL: " . ( $seo['canonical'] ?: '(Auto-generated)' );
    $output[] = "";
    $output[] = "OPEN GRAPH:";
    $output[] = "  Title: " . ( $seo['og_title'] ?: '(Not set)' );
    $output[] = "  Description: " . ( $seo['og_description'] ?: '(Not set)' );
    $output[] = "  Image: " . ( $seo['og_image'] ?: '(Not set)' );
    $output[] = "";
    $output[] = "Robots: " . ( $seo['robots'] ?: 'Default' );
    $output[] = "Schema Type: " . ( $seo['schema_type'] ?: 'None' );
    
    $seo['complete_data'] = implode( "\n", $output );
    
    return $seo;
}
// ==========================================
// GET THEME SETTINGS
// ==========================================
function wp_pages_get_theme_settings( $page_id ) {
    $output = [];
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "THEME SETTINGS";
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "";
    
    // Common theme meta keys
    $theme_keys = [
        '_wp_page_template',
        '_elementor_data',
        '_elementor_template_type',
        'sidebar_layout',
        'hide_title',
        'custom_css',
        'page_layout',
        'header_layout',
        'footer_layout',
    ];
    
    $found_settings = false;
    
    foreach ( $theme_keys as $key ) {
        $value = get_post_meta( $page_id, $key, true );
        if ( ! empty( $value ) ) {
            $found_settings = true;
            if ( is_array( $value ) || is_object( $value ) ) {
                $output[] = "{$key}:";
                $output[] = print_r( $value, true );
            } else {
                $output[] = "{$key}: {$value}";
            }
        }
    }
    
    if ( ! $found_settings ) {
        $output[] = "No theme-specific settings detected.";
    }
    
    return implode( "\n", $output );
}
// ==========================================
// GET CUSTOM TAXONOMIES
// ==========================================
function wp_pages_get_custom_taxonomies( $page_id ) {
    $taxonomies = get_object_taxonomies( 'page', 'objects' );
    
    if ( empty( $taxonomies ) ) {
        return 'No custom taxonomies registered for pages.';
    }
    
    $output = [];
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "CUSTOM TAXONOMIES";
    $output[] = "═══════════════════════════════════════════════";
    $output[] = "";
    
    $found_terms = false;
    
    foreach ( $taxonomies as $taxonomy ) {
        $terms = wp_get_post_terms( $page_id, $taxonomy->name );
        
        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
            $found_terms = true;
            $output[] = strtoupper( $taxonomy->label ) . ":";
            foreach ( $terms as $term ) {
                $output[] = "  • {$term->name} (slug: {$term->slug}, ID: {$term->term_id})";
            }
            $output[] = "";
        }
    }
    
    if ( ! $found_terms ) {
        $output[] = "No custom taxonomy terms assigned to this page.";
    }
    
    return implode( "\n", $output );
}
// ==========================================
// AUTO-SYNC HOOKS
// ==========================================
// Hook 1: Page save/update
add_action( 'save_post_page', function( $page_id, $page, $update ) {
    // Avoid infinite loops and autosaves
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( wp_is_post_revision( $page_id ) ) return;
    
    error_log( 'WP_PAGES_SYNC: save_post_page fired for page ' . $page_id );
    wp_pages_mirror_page_to_cpt( $page );
}, 20, 3 );
// Hook 2: Page deletion
add_action( 'before_delete_post', function( $page_id ) {
    $post = get_post( $page_id );
    if ( ! $post || $post->post_type !== 'page' ) return;
    
    error_log( "WP_PAGES_SYNC: Page {$page_id} is being deleted - removing associated sync post" );
    
    // Find the sync post for this page
    $query = new WP_Query( [
        'post_type'      => 'wp_pages_sync',
        'posts_per_page' => 1,
        'fields'         => 'ids',
        'meta_query'     => [
            [
                'key'   => 'page_id',
                'value' => absint( $page_id ),
            ]
        ]
    ] );
    
    if ( ! empty( $query->posts ) ) {
        wp_delete_post( $query->posts[0], true );
        error_log( "WP_PAGES_SYNC: Deleted sync post for page {$page_id}" );
    }
}, 10, 1 );
// Hook 3: Periodic cleanup
add_action( 'load-edit.php', function() {
    if ( ! isset( $_GET['post_type'] ) || $_GET['post_type'] !== 'wp_pages_sync' ) {
        return;
    }
    
    // Only run cleanup occasionally (using transient to limit frequency)
    if ( get_transient( 'wp_pages_sync_cleanup_done' ) ) {
        return;
    }
    
    wp_pages_cleanup_orphaned_posts();
    
    // Set transient to prevent running too often (once per hour)
    set_transient( 'wp_pages_sync_cleanup_done', true, HOUR_IN_SECONDS );
} );
// Verify CPT exists on init
add_action( 'init', function() {
    if ( ! post_type_exists( 'wp_pages_sync' ) ) {
        error_log( 'WP_PAGES_SYNC: CPT wp_pages_sync not registered!' );
    } else {
        error_log( 'WP_PAGES_SYNC: Sync engine loaded successfully' );
    }
}, 999 );

Comments

Add a Comment