woocommerce export orders in text file

Home » Snippets » woocommerce export orders in text file
0

Created with:

Visibility: 

public

Creator: contact@arcensoft.com

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
// Plugin Header and other code

function wpturbo_export_orders() {
    // Get WooCommerce orders
    $args = array(
        'status' => array( 'completed', 'processing' ),
        'limit' => -1,
    );
    $orders = wc_get_orders( $args );

    // Prepare the content for the text file
    $content = '';
    foreach ( $orders as $order ) {
        $content .= "Order ID: " . $order->get_id() . "n";
        $content .= "Order Total: " . $order->get_formatted_order_total() . "n";
        $content .= "Customer Name: " . $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() . "n";
        $content .= "Email: " . $order->get_billing_email() . "n";
        $content .= "-------------------------n";
    }

    // Export the content to a text file
    $file_path = WP_CONTENT_DIR . '/my-orders.txt';
    $file_content = array(
        'headers' => array(
            'Content-Type' => 'text/plain',
        ),
        'body' => $content,
    );
    $response = wp_remote_request( $file_path, array(
        'method' => 'POST',
        'httpversion' => '1.1',
        'sslverify' => false,
        'timeout' => 20,
        'redirection' => 5,
        'blocking' => true,
        'headers' => $file_content['headers'],
        'body' => $file_content['body'],
        'cookies' => array(),
    ) );

    // Check if the request was successful
    if ( is_wp_error( $response ) ) {
        // Handle error
        return;
    }

    // Do something else with the exported file

    // Plugin Footer and other code
}
add_action( 'init', 'wpturbo_export_orders' );
				

Explanation:

This code snippet demonstrates how to export WooCommerce orders into a text file using the wp_remote_request function. First, we retrieve the orders from WooCommerce using the wc_get_orders function, filtering by desired order statuses (completed and processing in this example). Then, we iterate through each order and append relevant information like order ID, order total, customer name, and email to the $content variable.

Next, we define the file path for the text file using the WP_CONTENT_DIR constant and specify the content type as plain text. We then make a POST request to the file path using wp_remote_request with the prepared headers and content. If the request is successful, you can perform additional actions with the exported file.

Remember to include this code in your wp-plugin.php file and customize it as needed. Also, make sure to test it thoroughly before deploying it on a live site.

Register an account to save your snippets or go Pro to get more features.