Home / Admin / Media sync script
Duplicate Snippet

Embed Snippet on Your Site

Media sync script

Code Preview
php
<?php
add_action( 'admin_init', 'media_sync_library' );
function media_sync_library() {
    // Folder inside uploads to scan
    $scan_folder = '/2026/02';
    $upload_dir = wp_upload_dir();
    $base_dir = $upload_dir['basedir'];
    $base_url = $upload_dir['baseurl'];
    $target_dir = $base_dir . $scan_folder;
    // Stop if folder doesn't exist
    if( ! is_dir( $target_dir ) ) {
        return;
    }
    // Load required WP functions
    require_once ABSPATH . '/wp-admin/includes/image.php';
    // Allowed image extensions
    $allowed = array( 'jpg', 'jpeg', 'png', 'gif', 'webp' );
    // Recursive folder scan
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator( $target_dir )
    );
    foreach( $iterator as $file ) {
        if( $file->isDir() ) continue;
        $file_path = $file->getPathname();
        // Check extension
        $ext = strtolower( pathinfo( $file_path, PATHINFO_EXTENSION ) );
        if( ! in_array( $ext, $allowed ) ) continue;
        // Relative path for URL
        $relative_path = str_replace( $base_dir, '', $file_path );
        $file_url = $base_url . $relative_path;
        // Duplicate Check
        $existing_id = attachment_url_to_postid( $file_url );
        if( $existing_id ) {
            continue;
        }
        // File type
        $filetype = wp_check_filetype( basename( $file_path ), null );
        // Create attachment
        $attachment = array(
            'post_mime_type' => $filetype['type'],
            'post_title' => sanitize_file_name( basename( $file_path ) ),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        $attach_id = wp_insert_attachment( $attachment, $file_path );
        // Generate metadata + thumbnails
        $attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
        wp_update_attachment_metadata( $attach_id, $attach_data );
    }
}

Comments

Add a Comment