I've got nested dropdown & I get format problems with more than 2 times nested items. Im pretty sure my "Mona Lisa" quality image made in Paint will demonstrate it perfectly.
Im looking for any suggestions what to change about my code to make it work properly.
IMAGE ABOUT MY PROBLEM:
CODE:
<div class="form-group">
<label for="p-location"><?php _e( 'Location', 'tt' ); ?></label>
<select name="p-location" id="p-location" class="form-control required" title="<?php _e( 'Please select the location.', 'tt' ); ?>" data-placeholder="<?php _e( 'Choose a location', 'tt' ); ?>">
<option value=""></option>
<?php
$locations = get_terms('p-location', array( 'orderby' => 'slug', 'parent' => 0, 'hide_empty' => false) );
if ( isset( $_GET['p_location'] ) ) {
$get_location = $_GET['p_location'];
}
else {
$get_location = '';
}
$p_locations = get_the_terms( $p_id , 'p-location' );
if ( !empty( $p_locations ) ) {
foreach ( $p_locations as $p_location ) {
$get_location = $p_location->term_id;
break;
}
}
?>
<?php foreach ( $locations as $key => $location ) : ?>
<option value="<?php echo $location->term_id; ?>" <?php selected( $location->term_id, $get_location ); ?>>
<?php
echo $location->name;
$location2 = get_terms( 'p-location', array( 'orderby' => 'slug', 'parent' => $location->term_id, 'hide_empty' => false ) );
if( $location2 ) :
?>
<optgroup>
<?php foreach( $location2 as $key => $location2 ) : ?>
<option value="<?php echo $location2->term_id; ?>" class="level2" <?php selected( $location2->term_id, $get_location ); ?>>
<?php
echo $location2->name;
$location3 = get_terms( 'p-location', array( 'orderby' => 'slug', 'parent' => $location2->term_id, 'hide_empty' => false ) );
if( $location3 ) : ?>
<optgroup>
<?php foreach( $location3 as $key => $location3 ) : ?>
<option value="<?php echo $location3->term_id; ?>" class="level3" <?php selected( $location3->term_id, $get_location ); ?>>
<?php
echo $location3->name;
$location4 = get_terms( 'p-location', array( 'orderby' => 'slug', 'parent' => $location3->term_id, 'hide_empty' => false ) );
if( $location4 ) :
?>
<optgroup>
<?php foreach( $location4 as $key => $location4 ) : ?>
<option value="<?php echo $location4->term_id; ?>" class="level4" <?php selected( $location4->term_id, $get_location ); ?>>
<?php echo $location4->name; ?>
</option>
<?php endforeach; ?>
</optgroup>
<?php endif; ?>
</option>
<?php endforeach; ?>
</optgroup>
<?php endif; ?>
</option>
<?php endforeach; ?>
</optgroup>
<?php endif; ?>
</option>
<?php endforeach; ?>
</select>
</div>