WooCommerce REST Client API – Create Product

I am currently using the client-API to implement a simple user front-end to upload products. The function client->products->create() seems to work fine, how ever I can’t get around one issue. Every time I upload a product, the vendor is set to the admin user instead of the user that is currently logged in. Is there a way to set the vendor through the API? Has anybody get done this?

This is the function I created that is called by AJaX when the form is submitted (I left key and website fields empty here on purpose):

Read More

function addProduct()
{

$options = array(
    'debug'           => false,
    'return_as_array' => false,
    'validate_url'    => false,
    'timeout'         => 30,
    'ssl_verify'      => false,
);

try {

    $client = new WC_API_Client( '', '', '', $options );

    $productName = $_POST["productname"];
    $price = $_POST["price"];
    $discountPrice = $_POST["discountPrice"];
    $description = $_POST["description"];
    $shortDescription = $_POST["shortDescription"];
    $authorId = 5;

    $client->products->create( array( 'title' => $productName, 'type' => 'simple', 'regular_price' => $price, 'description' => $description));


} catch ( WC_API_Client_Exception $e ) {

    echo $e->getMessage() . PHP_EOL;
    echo $e->getCode() . PHP_EOL;

    if ( $e instanceof WC_API_Client_HTTP_Exception ) {

        print_r( $e->get_request() );
        print_r( $e->get_response() );
    }
}

echo ("Publicado". $authorId);

// Una función AJaX en WordPress debe siempre terminarse con die().
die();  

}

Related posts

1 comment

  1. Yes your code seems to be perfect.

    The issue which you identified is because you might be using admin’s consumer key and consumer secret key each time which creating a product.
    You need to get the current user consumer secret key and consumer key for the operation to be performed by the user.

    Note: Make sure all users from whom you want to create products have permission set as both read and write.

    Try the above approach and let me know if it worked for you.

Comments are closed.