ccc

API REST Wordpress: Añadir, modificar, borrar y listar productos de Woocommerce

Para añadir:
if (isset($arr->token)) {
echo "TOKEN:".$arr->token."<hr>";
$authorization = "Authorization: Bearer ".$arr->token;
// dar de alta un post
$data = array(
'name' => 'Premium Quality',
    'type' => 'simple',
    'regular_price' => '21.99',
    'description' => 'Producto de woocommerce creado dinámicamente',
    'short_description' => 'Producto de woocommerce creado dinámicamente',
    'categories' => [
        [
            'id' => 21
        ],
        [
            'id' => 17
        ]
    ],
    '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'
        ]
    ]
);
$data_string = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://midominio.com/wp-json/wc/v3/products");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization ));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $result = curl_exec($ch);
    curl_close($ch);
}


Si queremos modificar solo habría que cambiar:
$data = array(
    'regular_price' => '66.66'
);
...
curl_setopt($ch, CURLOPT_URL, "https://midominio.com/wp-json/wc/v2/products/93");


Para borrar un producto concreto:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://midominio.com/wp-json/wc/v2/products/93");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization ));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);


Para listar todos los productos:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://midominio.com/wp-json/wc/v3/products?search=a&orderby=title&order=asc");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization ));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
$arr = json_decode($result);
// print_r($arr);
foreach ($arr as $clave=>$valor) {
    echo $valor->id.":".$valor->slug."<hr>";
}


Para ver todo lo que se puede hacer con la API: http://woocommerce.github.io/woocommerce-rest-api-docs/?php#create-a-product

No hay comentarios:

Publicar un comentario