我在我的自定义插件中使用碳字段来制作一些字段。我需要几个不同的字段,其中用户可以从 woocommerce 产品类别列表中选择类别。所以为此我制作了这样的代码
<?php
use Carbon_Fields\Container;
use Carbon_Fields\Field;
Class asd_plugin_Settings {
function __construct() {
add_action( 'init', array($this, 'get_cats') );
add_action( 'carbon_fields_register_fields', array($this,'crb_attach_theme_options') );
add_action( 'after_setup_theme', array($this,'make_crb_load') );
}
public function crb_attach_theme_options() {
Container::make( 'theme_options', __( 'Theme Options', 'crb' ) )
->add_fields( array(
Field::make( "multiselect", "crb_available_cats", "Category" )
->add_options( $this->get_product_cats() ),
) );
}
public function make_crb_load() {
require_once( ASD_PLUGIN_PATH . '/carbon-fields/vendor/autoload.php' );
\Carbon_Fields\Carbon_Fields::boot();
}
public function get_cats() {
$categories = get_terms( 'product_cat', 'orderby=name&hide_empty=0' );
$cats = array();
if ( $categories )
foreach ( $categories as $cat )
$cats[$cat->term_id] = esc_html( $cat->name );
print_r($cats); //getting category properly
}
public function get_product_cats() {
$categories = get_terms( 'product_cat', 'orderby=name&hide_empty=0' );
$cats = array();
if ( $categories )
foreach ( $categories as $cat )
$cats[$cat->term_id] = esc_html( $cat->name );
return $cats; //not getting category. Showing error invalid taxonomy
}
}
在这里,您可以看到我在 init 钩子中获得了相同的类别,但在 after_setup_theme 钩子中我没有获得这些类别。
除了 after_setup_theme 挂钩之外,Carbon 字段也无法正常工作。那么如何获取我所在领域的类别和产品呢?