0

我正在使用 WooCommerce 为 WordPress 编写插件。我需要在插件的管理页面'product_cat'中获取 WooCommerce 产品类别(分类)列表(注意对“管理页面”的强调)。但是,通过分类对过滤的调用和过滤会导致错误(我已经简化了代码。子菜单类在其他地方,据我所知它不会干扰):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_loadedwoocommerce_init.

4

1 回答 1

-1

好吧,我不知道到底发生了什么,但现在它正在使用init钩子工作。我之前试过,但没有,不知道为什么。现在我只做了 2 个测试:使用函数current_filter()检查函数本身是否正确挂钩;并挂钩到init包含对 . 的调用的函数get_terms($args)。然后我注意到它正在工作,我撤消了更改,一切正常。鬼失败。

于 2020-10-24T20:49:03.000 回答