插件内WooCommerce REST API调用失败问题求助
问题分析与解决方案
先看核心错误:PHP Fatal error: Uncaught Error: Call to undefined method WooCommerce::get() in ...,本质是全局变量名冲突导致的问题。
你在插件顶部实例化了Automattic\WooCommerce\Client对象,并赋值给了$woocommerce变量,但WordPress/WooCommerce本身已经有一个全局的$woocommerce变量——它指向的是WooCommerce的主核心类,而非REST API的Client类。当你在etsy_func()里用global $woocommerce时,拿到的是WooCommerce主类实例,自然找不到post()方法(日志里的get()可能是记录偏差,但核心都是方法不存在)。
本地单独测试没问题,是因为那里没有WordPress环境,没有预定义的$woocommerce全局变量,你的Client实例能正常使用;但集成到插件后,WordPress自带的全局变量覆盖了你的实例,就出问题了。
快速修复:修改全局变量名避免冲突
最简单的解决方式是把你的Client实例换个变量名,比如$wc_rest_client,避开和WooCommerce自带变量的冲突。修改后的代码如下:
<?php require __DIR__ . '/vendor/autoload.php'; use Automattic\WooCommerce\Client; // 更换变量名,避免冲突 $wc_rest_client = new Client( 'http://localhost/wordpress', 'ck_cb93e80be8b5866514b5e95f71055e3a8f2358d2', 'cs_a0ec55a88a28475373a8ece2e303c40634f56511', [ 'wp_api' => true, 'version' => 'wc/v3' , 'verify_ssl' => false ] ); function register_my_custom_submenu_page() { add_submenu_page( 'woocommerce', 'Etsy', 'Etsy', 'manage_options', 'etsy-link', 'etsy_func' ); } add_action('admin_menu', 'register_my_custom_submenu_page',99); function etsy_func() { echo '<h3>Title</h3>'; $data = [ 'name' => 'Premium Qualityssssssssssssss', 'type' => 'simple', 'regular_price' => '22.99', 'description' => 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.', 'short_description' => 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.', 'categories' => [ [ 'id' => 10 ], [ 'id' => 14 ] ], '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' ] ] ]; // 调用新的全局变量 global $wc_rest_client; print_r($wc_rest_client->post('products', $data)); } ?>
更优雅的优化:避免全局变量
全局变量不是WordPress插件开发的最佳实践,推荐用静态单例的方式封装Client实例,既避免重复实例化,也不用全局变量:
function get_wc_rest_client() { static $client; if (null === $client) { require __DIR__ . '/vendor/autoload.php'; use Automattic\WooCommerce\Client; $client = new Client( 'http://localhost/wordpress', 'ck_cb93e80be8b5866514b5e95f71055e3a8f2358d2', 'cs_a0ec55a88a28475373a8ece2e303c40634f56511', [ 'wp_api' => true, 'version' => 'wc/v3' , 'verify_ssl' => false ] ); } return $client; } // 在etsy_func里调用 function etsy_func() { echo '<h3>Title</h3>'; // ...$data定义部分不变 $wc_rest_client = get_wc_rest_client(); print_r($wc_rest_client->post('products', $data)); }
这种写法更符合WordPress的开发规范,也让代码更易维护。
内容的提问来源于stack exchange,提问作者Emil EV
相关产品推荐
相关产品推荐

