Support » Plugin: Carbon Fields » Querying and looping categories or posts within a complex/select field

  • Resolved peperene5150

    (@peperene5150)


    Hey there,

    I’m trying to retrieve categories within a field (make method).
    Basically I’m trying to achieve the following:

    $argsCat = array(
        'orderby' => 'ID',
        'order' => 'ASC'
    );
    $categories = get_categories( $argsCat );
    
    // My field
    Container::make('post_meta', __( 'My field' ) )
        ->show_on_post_type('page')
        ->add_fields( array(
    
            // gallery
            Field::make( 'complex', 'h_hero_slider', __( 'Ajouter un slide' ) )
                ->add_fields( '', [
                    Field::make( 'select', 'cat', 'Cat├ęgorie slider' )
                    ->set_width(50)
                    ->add_options( array(
                        foreach ( $categories as $category ) :
                            '$category->cat_ID' => '$category->name'
                        endforeach;
                    ) )
                    ->set_required( true ),
                ]),
        ));

    But it appears that looping within the add_options part doesn’t work at all.
    Do you have an idea?

    Thx for your precious help!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Contributor Atanas Angelov

    (@atanasangelovdev)

    Hi @peperene5150,

    You are close to what you need but calling foreach inside an array declaration is not valid php syntax which is what causes the error.

    I’ve updated your code here which should do the job:

    
    function get_category_options() {
    	$argsCat = array(
    	    'orderby' => 'ID',
    	    'order' => 'ASC'
    	);
    	$categories = get_categories( $argsCat );
    
    	$options = array();
    	foreach ($categories as $term) {
    		$options[ $term->term_id ] = $term->name;
    	}
    	return $options;
    }
    
    // My field
    Container::make('post_meta', __( 'My field' ) )
        ->show_on_post_type('page')
        ->add_fields( array(
    
            // gallery
            Field::make( 'complex', 'h_hero_slider', __( 'Ajouter un slide' ) )
                ->add_fields( '', [
                    Field::make( 'select', 'cat', 'Cat├ęgorie slider' )
                    ->set_width(50)
                    ->add_options( 'get_category_options' )
                    ->set_required( true ),
                ]),
        ));
    

    In this case we’re making use of the ability of add_options to accept a function as it’s argument so that it lazyloads the options instead of loading them on every pageload.

    peperene5150

    (@peperene5150)

    Thank you Atanas,
    it works like a charm!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Querying and looping categories or posts within a complex/select field’ is closed to new replies.