事实证明,您可以在服务器上使用 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;
}