【发布时间】:2021-02-07 12:55:41
【问题描述】:
我正在使用 WooCommerce 为 WordPress 编写插件。我需要获取 WooCommerce 产品类别列表(分类法'product_cat')在插件的管理页面(注意“管理页面”的重点)。
然而,对get_categories() 和get_terms() 按分类过滤 的调用会导致错误(我已经简化了代码。子菜单类在其他地方,据我所知它不会干扰):
add_action( 'init', 'myplugin_admin_settings' );
function myplugin_admin_settings() {
$plugin = new Submenu( new MyPlugin_Admin_Page('myplugin_options') );
$plugin->init();
}
class MyPlugin_Admin_Page {
public function __construct($option_name) {
$args = array(
'taxonomy' => 'product_cat',
'hide_empty' => false
);
var_export(get_categories( $args )); // Prints 'error'
var_export(get_terms( $args )); // Prints 'error'
var_export(get_terms()); // Prints the whole list of terms including those belonging to 'product_cat' taxonomy
}
}
打印的错误是:
WP_Error::__set_state(array( 'errors' => array ( 'invalid_taxonomy' => array ( 0 => 'Invalid taxonomy.', ), ), 'error_data' => array ( ),))array ( '' => NULL,)
这表明分类法不存在。事实上,如果我打电话给taxonomy_exists('product_cat'),它会说false。但是,打印的整个术语列表包括属于 'product_cat' 的术语,如果分类不存在,这似乎是不可能的。这要了我的命。举个例子:
43 =>
WP_Term::__set_state(array(
'term_id' => 56,
'name' => 'Accesorios',
'slug' => 'accesorios',
'term_group' => 0,
'term_taxonomy_id' => 56,
'taxonomy' => 'product_cat',
'description' => '',
'parent' => 0,
'count' => 1,
'filter' => 'raw',
)),
这些调用是在 init 挂钩中完成的,因此它们应该返回产品类别。
任何人都可以理解发生了什么?还有其他方法可以在管理页面中获取产品类别吗?
谢谢。
编辑:我也尝试过使用钩子 plugins_loaded 和 woocommerce_init。
【问题讨论】:
标签: php wordpress woocommerce wordpress-plugin-creation