Effortlessly Automating Imports with WP All Import: A Custom Solution

As a developer, we often encounter unique challenges that require creative problem-solving. Recently, I had an intriguing requirement: to upload the same CSV file to two separate WP All Import templates and trigger the imports programmatically. After diving into the task, tweaking the code, and learning along the way, I crafted a seamless solution. Today, I’m thrilled to share this process with you—complete with code and insights—so you can implement it in your own projects.

The Requirement

The goal was straightforward but tricky:

  1. Upload a single CSV file via a custom WordPress admin form.
  2. Assign the uploaded file to two pre-configured WP All Import templates.
  3. Programmatically trigger both imports.

Building the Custom Upload Form

To begin, I added a custom admin page where I could upload the CSV file. This required creating a new menu item in the WordPress dashboard, a form to handle file uploads, and logic to process the file.

Here’s how I created the admin page and file upload form:

php

// Add a custom menu page

add_action( ‘admin_menu’, ‘custom_import_csv_menu’ );

function custom_import_csv_menu() {

    add_menu_page(

        ‘Fabrics Import’,          // Page title

        ‘Fabrics Import’,          // Menu title

        ‘manage_options’,          // Capability

        ‘fabric-import’,           // Menu slug

        ‘custom_import_csv_page’,  // Callback function

        ‘dashicons-upload’,        // Icon

        30                         // Position

    );

}

// Render the upload form

function custom_import_csv_page() {

    ?>

    <div class=”wrap”>

        <h1>Fabrics Import</h1>

        <form method=”post” enctype=”multipart/form-data” action=”admin-post.php”>

            <?php wp_nonce_field( ‘csv_import_action’, ‘csv_import_nonce’ ); ?>

            <input type=”hidden” name=”action” value=”import_csv”>

            <table class=”form-table”>

                <tr valign=”top”>

                    <th scope=”row”>Upload CSV File</th>

                    <td><input type=”file” name=”csv_file” accept=”.csv” /></td>

                </tr>

            </table>

            <?php submit_button( ‘Import CSV’ ); ?>

        </form>

    </div>

    <?php

}

This form ensures only CSV files are accepted and secures the process with a nonce.

Handling the CSV Upload

When the file is uploaded, it triggers the admin_post_import_csv action. Here’s how I handled the file upload and initiated the import:

php

// Process the uploaded CSVt7

add_action( ‘admin_post_import_csv’, ‘handle_csv_import’ );

function handle_csv_import() {

    if ( ! isset( $_POST[‘csv_import_nonce’] ) || 

         ! wp_verify_nonce( $_POST[‘csv_import_nonce’], ‘csv_import_action’ ) ) {

        die( ‘Permission denied’ );

    }

    if ( ! current_user_can( ‘manage_options’ ) ) {

        die( ‘Permission denied’ );

    }

    if ( isset( $_FILES[‘csv_file’] ) && ! empty( $_FILES[‘csv_file’][‘tmp_name’] ) ) {

        $uploaded_file = $_FILES[‘csv_file’];

        // Validate the file type

        $file_type = wp_check_filetype( $uploaded_file[‘name’] );

        if ( ‘csv’ !== $file_type[‘ext’] ) {

            die( ‘Please upload a valid CSV file.’ );

        }

        // Move the file to the uploads directory

        $upload_dir = wp_upload_dir();

        $file_path = $upload_dir[‘path’] . ‘/’ . basename( $uploaded_file[‘name’] );

        if ( move_uploaded_file( $uploaded_file[‘tmp_name’], $file_path ) ) {

            import_csv_into_two_imports( $file_path );

            wp_redirect( add_query_arg( ‘import’, ‘success’, wp_get_referer() ) );

            exit;

        } else {

            die( ‘File upload failed.’ );

        }

    } else {

        die( ‘No file uploaded.’ );

    }

}

Triggering WP All Import Programmatically

The exciting part: running two imports programmatically. WP All Import provides a powerful API, allowing us to execute imports directly with custom code.

Here’s how I updated the file path in the database and executed the imports:

php

// Function to import CSV into two separate imports using Import IDs

function import_csv_into_two_imports( $csv_file_path ) {

    if ( ! class_exists( ‘PMXI_Import_Record’ ) ) {

        die( ‘WP All Import plugin is not active or not found.’ );

    }

    // Define your Import IDs (replace with actual import IDs)

    $import_id_1 = 7; // Replace with your first Import ID

    $import_id_2 = 6; // Replace with your second Import ID

    // Run the first import

    $import_1_result = run_wp_all_import_by_id( $csv_file_path, $import_id_1 );

    if ( $import_1_result ) {

        echo ‘First import completed successfully. Import ID: ‘ . $import_1_result . ‘<br>’;

    } else {

        echo ‘Failed to execute the first import.<br>’;

    }

    // Run the second import

    $import_2_result = run_wp_all_import_by_id( $csv_file_path, $import_id_2 );

    if ( $import_2_result ) {

        echo ‘Second import completed successfully. Import ID: ‘ . $import_2_result . ‘<br>’;

    } else {

        echo ‘Failed to execute the second import.<br>’;

    }

}

function run_wp_all_import_by_id( $csv_file_path, $import_id ) {

    global $wpdb;

    // Ensure the WP All Import class is available

    if ( ! class_exists( ‘PMXI_Import_Record’ ) ) {

        die( ‘WP All Import plugin is not active or not found.’ );

    }

    // Update the file path in the database

    $updated = $wpdb->update(

        $wpdb->prefix . ‘pmxi_imports’,

        array( ‘path’ => $csv_file_path ), // Set the new file path

        array( ‘id’ => $import_id ), // Where clause for specific import ID

        array( ‘%s’ ),

        array( ‘%d’ )

    );

    if ( $updated === false ) {

        die( ‘Failed to update the import file path in the database.’ );

    }

    // Load the import record

    $import = new PMXI_Import_Record();

    $import->getById( $import_id );

    if ( $import->isEmpty() ) {

        die( ‘Import record not found.’ );

    }

    try {

        // Initialize the scheduled import process

        $scheduledImport = new \Wpai\Scheduling\Import();

        // Trigger the import process

        $history_log = $scheduledImport->trigger( $import );

        // Process the import

        $response = $scheduledImport->process( $import, $logger );

        // Define the logger function to output messages

        $logger = function ( $m ) {

            print( “<p>[” . date( “H:i:s” ) . “] ” . wp_all_import_filter_html_kses($m) . “</p>\n” );

        };

        // Apply logger filters

        $logger = apply_filters(‘wp_all_import_logger’, $logger);

        // Run the import immediately

        $import->execute( $logger, false, true );

        // Log success

        error_log( “Successfully ran import ID: {$import_id}” );

        return $import_id;

    } catch ( Exception $e ) {

        // Catch any errors during the import process

        error_log( ‘Error running import: ‘ . $e->getMessage() );

        die( ‘Error running import: ‘ . $e->getMessage() );

    }

    return false;

}

The Results

When the form is submitted, the CSV is uploaded, assigned to both imports, and executed in sequence. The process ensures that both templates process the same data efficiently.

What I Loved About This Process

  • The flexibility of WP All Import made it easy to integrate with custom workflows.
  • The thrill of watching two imports execute simultaneously after a single file upload was immensely satisfying!
  • The structured approach of splitting tasks into logical functions kept the code clean and reusable.

Why This Matters

Many clients or projects demand automation for recurring tasks. By automating imports, I saved hours of manual work and ensured consistency. This solution is scalable and adaptable, opening doors to more creative automation possibilities.

Sameed Fazal

I currently work at Codup, leading a cross-functional team to create innovative products that empower people in their careers. With over 11 years of expertise in WordPress and PHP, I am passionate about developing loved and trusted solutions for WooCommerce and WordPress.

Follow author on: