wordpress carbon fields get category list and products in plugin fields

1.8k Views Asked by At

I am using carbon fields in my custom plugin to make some fields. There I need couple of different fields with field where user can select category from a list of woocommerce product category. So for that I made my code like this

<?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
    }

}

Here you can see that I am getting the same categories in init hook but in after_setup_theme hook I am not getting those categories.

Carbon fields also doesn't work properly except after_setup_theme hook. So how can I get categories and products in my fields?

1

There are 1 best solutions below

0
On

Disclosure: I am the former maintainer of Carbon Fields (up to 2.2).

Since most post types and taxonomies are not available so early in the WordPress request lifecycle, you will need to use a callable instead of passing the results directly to add_options(). See the NB! Performance implications section for more reasons why you should prefer to use callables: https://carbonfields.net/docs/fields-select/?crb_version=2-2-0

So your code should look something like this:

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

This way the callable will be called much later in the lifecycle (and will only be called when needed, not on every request).