Search code examples
phphtmlwordpressbootstrap-4dropdown

How to make a dropdown in a foreach of specific data


I need to push the results of an array into a bs dropdown how do i do that?

This is what i have

<?php
$translations = pll_the_languages(array('raw' => 1));

$lang_codes = array();

foreach ($translations as $lang => $info) {

    $lang_codes[$lang] = [
        'slug' => $info['slug'],
        'url' => $info['url'],
        'flag' => $info['flag']
    ];
}

?>

Result:

array(2) { 
 ["de"]=> array(3) { 
  ["slug"]=> string(2) "de" ["url"]=> string(34) "http://localhost/werk/Mol/de/haus/" ["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/de.png" 
 } 
 ["nl"]=> array(3) { 
  ["slug"]=> string(2) "nl" ["url"]=> string(26) "http://localhost/werk/Mol/" ["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/nl.png" 
 } 
}

How to push this result with the foreach into this bootstrap dropdown with the slug as the value and url as the link.

 <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
  <a class="dropdown-item" href="#">Action</a>
  <a class="dropdown-item" href="#">Another action</a>
  <a class="dropdown-item" href="#">Something else here</a>
 </div>

Solution

  • This would do it:

    echo '<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">';
    foreach ( $lang_codes as $info ) {
        echo '<a class="dropdown-item" href="' . esc_url( $info['url'] ) . '">' .
            esc_html( $info['slug'] ) . '</a> ';
    }
    echo '</div>';
    

    Or you might be looking for this (?), which simply loops through the $translations array without having to create the $lang_codes array:

    echo '<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">';
    foreach ( $translations as $info ) {
        echo '<a class="dropdown-item" href="' . esc_url( $info['url'] ) . '">' .
            esc_html( $info['name'] ) . '</a> ';
    }
    echo '</div>';
    

    And in the above code, I used $info['name'] (i.e. the language name; see the reference) and not $info['slug'], but you can of course change it if you want.