Jump to content

Combine values in foreach to create drop down


jarvis

Recommended Posts

Hi All,

 

I hope someone can help. I currently have the following code:

		$all_categories = get_categories( $args );

        // display a message as the first option
        $choices = array(array('text' => 'Please Select A Category', 'value' => 0 ));

        foreach ($all_categories as $cat){
			if($cat->category_parent == 0){
				$category_id = $cat->term_id;						
            	$choices[] = array( 'text' => $cat->name, 'value' => $cat->slug, 'isSelected' => false );
			}
        }

        $field['choices'] = $choices;

As you can see, it loops through a list of results and this is used to construct a drop down

 

The issue I've got, it only returns the top level of categories. In order to get categories and sub categories I need to alter the code to the following:

$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
	if($cat->category_parent == 0) {
		$category_id = $cat->term_id;       
		echo $cat->name .'<br/>';

		$args2 = array(
			'taxonomy'     => $taxonomy,
			'child_of'     => 0,
			'parent'       => $category_id,
			'orderby'      => $orderby,
			'show_count'   => $show_count,
			'pad_counts'   => $pad_counts,
			'hierarchical' => $hierarchical,
			'title_li'     => $title,
			'hide_empty'   => $empty
		);
		$sub_cats = get_categories( $args2 );
		if($sub_cats) {
			foreach($sub_cats as $sub_category) {
				echo  '  '.$sub_category->name.'<br/>';
			}   
		}
	}       
}

However, I can't then add the code I need as I now have 2 foreach loops

 

Is there anyway around this?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.