1

我在我的自定义插件中使用碳字段来制作一些字段。我需要几个不同的字段,其中用户可以从 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 字段也无法正常工作。那么如何获取我所在领域的类别和产品呢?

4

1 回答 1

1

披露:我是 Carbon Fields(最高 2.2)的前维护者。

由于大多数帖子类型和分类法在 WordPress 请求生命周期的早期不可用,因此您需要使用可调用对象而不是将结果直接传递给add_options(). NB! Performance implications有关您应该更喜欢使用可调用对象的更多原因, 请参阅该部分: https ://carbonfields.net/docs/fields-select/?crb_version=2-2-0

所以你的代码应该是这样的:

Container::make( 'theme_options', __( 'Theme Options', 'crb' ) )
    ->add_fields( array(
        Field::make( "multiselect", "crb_available_cats", "Category" )
            ->add_options( array( $this, 'get_product_cats' ) ),
    ) );

这样,可调用对象将在生命周期的后期被调用(并且只会在需要时调用,而不是在每次请求时调用)。

于 2018-05-09T08:26:45.483 回答