wordpress carbon字段在插件字段中获取类别列表和产品
我正在使用我的自定义插件制作一些字段。在那里,我需要两个不同的领域与领域,用户可以选择从一个产品类别列表类别。因此,我制作了这样的代码wordpress carbon字段在插件字段中获取类别列表和产品,wordpress,woocommerce,carbon-fields,carbon-fields-2,Wordpress,Woocommerce,Carbon Fields,Carbon Fields 2,我正在使用我的自定义插件制作一些字段。在那里,我需要两个不同的领域与领域,用户可以选择从一个产品类别列表类别。因此,我制作了这样的代码 <?php use Carbon_Fields\Container; use Carbon_Fields\Field; Class asd_plugin_Settings { function __construct() { add_action( 'init', array($this, 'get_cats') ); add_
<?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
}
}
披露:我是碳场的前维护者(最多2.2个)
由于大多数post类型和分类在WordPress请求生命周期的早期不可用,因此您需要使用可调用的,而不是将结果直接传递到add\u options()
。请参见NB!性能影响
部分了解您更喜欢使用可调用项的更多原因:
因此,您的代码应该如下所示:
Container::make( 'theme_options', __( 'Theme Options', 'crb' ) )
->add_fields( array(
Field::make( "multiselect", "crb_available_cats", "Category" )
->add_options( array( $this, 'get_product_cats' ) ),
) );
通过这种方式,可调用项将在生命周期的晚些时候调用(并且只在需要时调用,而不是在每次请求时调用)