Search code examples
phphtmlwordpresshtml-selectgravity-forms-plugin

WordPress: Add level indicator to category list


I display a list of categories as options of a select field. The problem is, that every category looks the same. Even if they are sub-categories.

For example, my category tree looks like this:

  • Main category
    • Sub category
      • Third level category

But in the select field it shows like this:

  • Main category
  • Sub category
  • Third level category

Here's my code to populate a select field in a form:

function populate_dropdown_with_product_categories( $form ) {
    //product_cat is the taxonomy for WooCommerce's products
    //get the terms for the product_cat taxonomy
    $product_categories = get_terms( 'product_cat', array('hide_empty' => false,) );

    //Creating drop down item array.
    $items = array();

    //Adding product category terms to the items array
    foreach ( $product_categories as $product_category ) {
        $items[] = array( 'value' => $product_category->name, 'text' => $product_category->name );
    }

    //Adding items to field id 6. Replace 6 with your actual field id. You can get the field id by looking at the input name in the markup.
    foreach ( $form['fields'] as &$field ) {
        if ( $field->id == 64 ) {
            $field->choices = $items;
        }
    }

    return $form;
}

I guess I need to add the level of the category in this line:

$items[] = array( 'value' => $product_category->name, 'text' => $product_category->name );

But how can I do that? For me it would be enough if every level gets a - (two - for third level...) before the name.

Something like this:

 - Main category
 -- Sub category 
 --- Third level category

Solution

  • I found a solution. I've changed the foreach code like this:

    foreach ( $product_categories as $product_category ) {
        $product_category_level = count( get_ancestors($product_category->term_id, 'product_cat'));
    
        if ($product_category_level == 1 ) :
            $product_category_level_indicator = '- ';
        elseif ($product_category_level == 2 ) :
            $product_category_level_indicator = '-- ';
        else:
            $product_category_level_indicator = '';
        endif;
    
        $items[] = array( 'value' => $product_category->name, 'text' => $product_category_level_indicator.$product_category->name );
    }
    

    It works for me. Feedback is appreciated.