我做了一个插件,所以我可以有自定义端点。最终,我想提取有关我的可预订产品(woocommerce 预订)的数据。
这是我的插件:
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins',
get_option( 'active_plugins' ) ) ) ) {
// Define constants.
define( 'CUSTOM_ENDPOINTS_PLUGIN_VERSION', '1.0.0' );
define( 'CUSTOM_ENDPOINTS_PLUGIN_DIR', __FILE__ );
// Include the main class.
require plugin_dir_path( __FILE__ ) . '/class-rest-custom-woocommerce-endpoints.php';
}
然后在我的主类文件中:
add_action( 'woocommerce_loaded', 'get_data');
add_action( 'rest_api_init', 'custom_endpoint_first');
function custom_endpoint_first(){
register_rest_route( 'cwe/v1/booking', '/get-data',
array(
'methods' => 'GET',
'callback' => 'get_data')
);
}
function get_data() {
$args = array( 'include' => array(28));
$products = wc_get_products( $args );
return $products;
}
我不知道为什么它返回一个空数组,但是当我调用我的自定义 URL 时它有 200 状态。
最佳答案
使用此代码段以 JSON 格式获取产品。
public function get_products()
{
$p = wc_get_products(array('status' => 'publish'));
$products = array();
foreach ($p as $product) {
$products[] = $product->get_data();
}
return new WP_REST_Response($products, 200);
}
关于php - wc_get_products 返回空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54639296/