我应该在服务器上使用什么 WooCommerce API?

What WooCommerce API should I use on the server?

我正在编写一个脚本来批量更改产品属性,例如价格、重量和尺寸。我需要直接在安装了 WordPress (4.7.2) 和 WooCommerce (2.6.13) 的服务器上 运行 脚本。我能想到的选项对我来说似乎不太理想:

  1. WooCommerce 非 REST API 将是我明显的选择,但它被降级为一个可怕的 legacy folder,闻起来已被弃用。
  2. WooCommerce REST API (link) 似乎矫枉过正:为什么我已经在服务器上并且可以通过身份验证并使用 HTTP只需使用 PHP?
  3. 考虑到 WooCommerce 产品属性之间的许多关系,
  4. 通过 update_post_meta() 作用于数据库 似乎容易出错且难以维护;只需看看 here 仅仅为了更改产品价格就必须复制的逻辑数量!
  5. WP-CLI 可以工作,但 AFAIK 它不会像 PHP 脚本那样灵活;无论如何,it is REST-powered 从 v3.0 开始,所以我想第 2 点也适用于此。

我觉得我错过了什么,请帮助我,否则我的大脑会爆炸:-D

事实证明,您可以在服务器上使用 REST API,而无需进行身份验证或执行 HTTP 请求:您只需要构建一个 WP_REST_Request 对象并将其直接传递给 API.

示例:显示产品

这是一个示例 PHP 脚本,它将使用 REST API 根据产品 ID 打印产品信息。脚本应放在WordPress文件夹中,并在浏览器中执行;产品 ID 作为查询参数给出,例如:http://www.yourwebsite.com/script.php?id=123.

<?php
/* Load WordPress */
require('wp-load.php');

/* Extract the product ID from the query string */
$product_id = isset( $_GET['id'] ) ? $_GET['id'] : false;

if ( $product_id ) {

    /* Create an API controller */
    $api = new WC_REST_Products_Controller();

    /* Build the request to create a new product */
    $request = new WP_REST_Request ('POST', '', '');
    $request['id'] = $product_id;

    /* Execute the request */
    $response = $api->get_item( $request );

    /* Print to screen the response from the API.
    The product information is in $response->data  */
    print_r( $response );

    /* Also print to screen the product object as seen by WooCommerce */
    print_r( wc_get_product( $product_id ) );

}

示例:创建产品

下一个脚本将创建一个新产品。产品的详细信息应直接在脚本中的 set_body_params() 函数中输入。对于允许字段的列表,只需使用前面的脚本打印任何产品的数据。

/* Load WordPress */
require('wp-load.php');

/* Create an API controller */
$api = new WC_REST_Products_Controller();

/* Build the request to create a new product */
$request = new WP_REST_Request ('POST', '', '');
$request->set_body_params( array (
    'name' => 'New Product',
    'slug' => 'new-product',
    'type' => 'simple',
    'status' => 'publish',
    'regular_price' => 60,
    'sale_price' => 40,
));

/* Execute the request */
$response = $api->create_item( $request );

/* Print to screen the response from the API */
print_r( $response );

/* Also print to screen the product object as seen by WooCommerce */
print_r( wc_get_product( $response->data['id'] ) );

一些基本的安全措施

在您的网站上留下可执行 PHP 脚本不是一个好主意。我宁愿将它们合并到一个插件中,并且只允许授权用户访问它们。为此,将以下代码添加到脚本中可能会很有用:

/* Load WordPress. Replace the /cms part in the path if
WordPress is installed in a folder of its own. */
try {
    require($_SERVER['DOCUMENT_ROOT'] . '/cms/wp-load.php');
} catch (Exception $e) {
    require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
}

/* Restrict usage of this script to admins */
if ( ! current_user_can('administrator') ) {
  die;
}

好吧,根据你的出色回答,我可以补充一点,你可以使用 wordpress api (v2.wp-api.org) 本身来 运行 作为一个功能,因此它将受到保护,您还可以添加身份验证以在您关心安全性的情况下执行。就像我通常喜欢为正常设置添加 2 个插件:api 工具箱(更改 api 路由 -> wp-json)和 wp 选项并编辑我的选项文件函数。