How to upload image to wordpress from external page

The question:

I have a webpage on localhost that do not have wordpress environment, I had use woocommerce api to create the product, however woocommerce api doesnt seem to upload the image.
I want to create the product and upload the image.
this the code I am using and the woocommerce api default.

<?php
$data = [
    'name' => 'Premium Quality',
    'type' => 'simple',
    'regular_price' => '21.99',
    'description' => 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.',
    'short_description' => 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.',
    'categories' => [
        [
            'id' => 9
        ],
        [
            'id' => 14
        ]
    ],
    'images' => [
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg'
        ],
        [
            'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg'
        ]
    ]
];

print_r($woocommerce->post('products', $data));
?>

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Just to make sure: You have a local environment, without WooCommerce, from which you want to create a product in your WooCommerce WordPress site, and make sure that the images you provide are uploaded to your WordPress site.

1. Install library

Make sure that you in your local environment have installed the WooCommerce REST API PHP Library.

composer require automattic/woocommerce

2. Create your script

Create a file called my_import_file.php

touch my_import_file.php

Edit that file with your favorite editor (or any editor).

Using Vim

vim my_import_file.php

Using Visual Studio Code (if you have the shell command installed)

code my_import_file.php

You need to:

Your file should look similar to this:

<?php
/**
 * Settings
 */
// Your WordPress site URL
DEFINE('WORDPRESS_BASE_URL', 'https://enter-your-wordpress-url-here');

// Your WordPress username
DEFINE('WORDPRESS_LOGIN', 'enter-your-wordpress-username-here');

// Create a new Application Password in dashboard /wp-admin/profile.php
DEFINE('WORDPRESS_APPLICATION_PASSWORD', 'enter-your-application-password-here');

// Create a new REST API key from your wordpress installation
// https://docs.woocommerce.com/document/woocommerce-rest-api/
DEFINE('WOOCOMMERCE_CONSUMER_KEY', 'enter-your-woocomemrce-consumer-key-here');
DEFINE('WOOCOMMERCE_CONSUMER_SECRET', 'enter-your-woocomemrce-consumer-secret-here');

// Load composers autoload
require __DIR__ . '/vendor/autoload.php';

// Use the WooComerce client
use AutomatticWooCommerceClient;

// Initiate the WooCommerce client
$woocommerce = new Client(
    WORDPRESS_BASE_URL,
    WOOCOMMERCE_CONSUMER_KEY,
    WOOCOMMERCE_CONSUMER_SECRET,
    [
        'version' => 'wc/v3',
    ]
);


// An array of all the images you want to upload. They can be local files or URL's.
// Any non existing images will be filtered out.
$images = array(
    "/Users/admin/Documents/nice-image-of-me.jpg",
    "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg",
    "string that is invalid"
);


// Define the product you want to create
$data = [
    'name' => 'Premium Quality',
    'type' => 'simple',
    'regular_price' => '21.99',
    'description' => 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.',
    'short_description' => 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.',
    'categories' => [
        [
            'id' => 9
        ],
        [
            'id' => 14
        ]
    ],
    'images' => prepare_array_of_images_for_wordpress($images)

];

// Create the product
$result = $woocommerce->post('products', $data);

// Print the result
print_r($result);




/**
 * Takes an array of images, strings or URL's and prepares for import.
 */
function prepare_array_of_images_for_wordpress(array $array_of_images){
    // Create empty array
    $images_to_upload = array();

    // Loop through the input, and process each entry
    foreach($array_of_images as $image){
        $images_to_upload[] = file_or_url_to_wordpress_image($image);
    }

    // Remove any unsucessful images from the array.
    return array_filter($images_to_upload);
}



/**
 * Takes a file or a url and uploads it to WordPress
 * Returns the image ID from the WordPress media gallery.
 */
function file_or_url_to_wordpress_image($image_path){

    // If the input is a URl, we can process it
    if (filter_var($image_path, FILTER_VALIDATE_URL)) {
        return ['src'=>$image_path];
    }

     // Make sure the image exist
    if (!file_exists($image_path)){return;}

    // Load the image
    $file = file_get_contents( $image_path );

    // Get the filename
    $filename = basename($image_path);

    // Initiate curl.
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt( $ch, CURLOPT_URL, WORDPRESS_BASE_URL .'/wp-json/wp/v2/media/' );
    curl_setopt( $ch, CURLOPT_POST, 1 );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, [
        "Content-Disposition: form-data; filename="$filename"",
        'Authorization: Basic ' . base64_encode( WORDPRESS_LOGIN. ':' . WORDPRESS_APPLICATION_PASSWORD ),
    ] );
    $result = curl_exec( $ch );
    curl_close( $ch );

    // Decode the response
    $api_response = json_decode($result);

    // Return the ID of the image that is now uploaded to the WordPress site.
    return ['id' => $api_response->id];
}

If you want to specify each image manually, you replace this line:

    'images' => prepare_array_of_images_for_wordpress($images)

With

    'images' => [
        [
            'id' => file_or_url_to_wordpress_image('path-to-image'),
            'other_option' => 'value'
        ],
        [
            'src' => file_or_url_to_wordpress_image('url-to-image'),
            'other_option' => 'value'
        ],
    ]

Just make sure you use 'id' if referring to an uploaded image, and 'src' when it’s a URL.

3. Run the script

Either in a browser, or from the command line using the following command:

php my_import_file.php

It should output something like this:

stdClass Object
(
    [id] => 736
    [name] => Premium Quality
    [slug] => premium-quality
     => https://localhost/p/uncategorized/premium-quality/
    [date_created] => 2021-06-12T18:01:08
    [date_created_gmt] => 2021-06-12T18:01:08
    [date_modified] => 2021-06-12T18:01:08
    [date_modified_gmt] => 2021-06-12T18:01:08
    [type] => simple
    [status] => publish
    [featured] => 
    [catalog_visibility] => visible
    [description] => Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
    [short_description] => Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
    [sku] => 
    [price] => 21.99
    [regular_price] => 21.99
    [sale_price] => 
    [date_on_sale_from] => 
    [date_on_sale_from_gmt] => 
    [date_on_sale_to] => 
    [date_on_sale_to_gmt] => 
    [on_sale] => 
    [purchasable] => 1
    [total_sales] => 0
    [virtual] => 
    [downloadable] => 
    [downloads] => Array
        (
        )

    [download_limit] => -1
    [download_expiry] => -1
    [external_url] => 
    [button_text] => 
    [tax_status] => taxable
    [tax_class] => 
    [manage_stock] => 
    [stock_quantity] => 
    [backorders] => no
    [backorders_allowed] => 
    [backordered] => 
    [low_stock_amount] => 
    [sold_individually] => 
    [weight] => 
    [dimensions] => stdClass Object
        (
            [length] => 
            [width] => 
            [height] => 
        )

    [shipping_required] => 1
    [shipping_taxable] => 1
    [shipping_class] => 
    [shipping_class_id] => 0
    [reviews_allowed] => 1
    [average_rating] => 0
    [rating_count] => 0
    [upsell_ids] => Array
        (
        )

    [cross_sell_ids] => Array
        (
        )

    [parent_id] => 0
    [purchase_note] => 
    [categories] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 27
                    [name] => Mat
                    [slug] => mat
                )

        )

    [tags] => Array
        (
        )

    [images] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 734
                    [date_created] => 2021-06-12T18:01:07
                    [date_created_gmt] => 2021-06-12T18:01:07
                    [date_modified] => 2021-06-12T18:01:07
                    [date_modified_gmt] => 2021-06-12T18:01:07
                    [src] => https://localhost/wp-content/uploads/2021/06/nice-image-of-me.jpg
                    [name] => nice-image-of-me
                    [alt] => 
                )

            [1] => stdClass Object
                (
                    [id] => 735
                    [date_created] => 2021-06-12T18:01:08
                    [date_created_gmt] => 2021-06-12T18:01:08
                    [date_modified] => 2021-06-12T18:01:08
                    [date_modified_gmt] => 2021-06-12T18:01:08
                    [src] => https://localhost/wp-content/uploads/2021/06/T_2_back-3.jpg
                    [name] => T_2_back-3.jpg
                    [alt] => 
                )

        )

    [attributes] => Array
        (
        )

    [default_attributes] => Array
        (
        )

    [variations] => Array
        (
        )

    [grouped_products] => Array
        (
        )

    [menu_order] => 0
    [price_html] => <span class="woocommerce-Price-amount amount"><bdi>21,99&nbsp;<span class="woocommerce-Price-currencySymbol">&euro;</span></bdi></span>
    [related_ids] => Array
        (
            [0] => 143
            [1] => 687
            [2] => 17
            [3] => 712
            [4] => 688
        )

    [meta_data] => Array
        (
        )

    [stock_status] => instock
    [brands] => Array
        (
        )

    [_links] => stdClass Object
        (
            [self] => Array
                (
                    [0] => stdClass Object
                        (
                            [href] => https://localhost/wp-json/wc/v3/products/736
                        )

                )

            [collection] => Array
                (
                    [0] => stdClass Object
                        (
                            [href] => https://localhost/wp-json/wc/v3/products
                        )

                )

        )

)

Method 2

I had achieve it by using I suspect the wp_api:

$img = 'C:/wamp64/www/leiria/img/2.1.jpg';
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'http://example-site.com/wp-json/wp/v2/media/' );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, file_get_contents( $img ) );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
        'Content-Disposition: form-data; filename="file_example_name.jpg"',
        'Authorization: Basic ' . base64_encode( 'wordpress_username:wordpress_password"' ), ] );
$result = curl_exec( $ch );
curl_close( $ch );




echo '<pre>';
print_r($result);
echo '</pre>';


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment