【问题标题】:Woocommerce Product Category taxonomy in Admin Pages管理页面中的 Woocommerce 产品类别分类
【发布时间】: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_loadedwoocommerce_init

【问题讨论】:

    标签: php wordpress woocommerce wordpress-plugin-creation


    【解决方案1】:

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

    【讨论】:

    • 我不明白为什么答案是 -1。它仍然可以给人们一些帮助,而不是我可以删除它或删除整个问题,我不在乎,但我认为它可以提示人们重新检查部分代码。以及为什么其他人建议使用 hook woocommerce_init 的评论不再存在了。
    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 2014-11-11
    • 2013-02-24
    • 2020-12-20
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多