0

Like the title says, I'm using wp_list_categories to get all of the existing categories of my website listed. I would like to achieve this:

<select class="filters-select">
   <option value=".category1">category1</option>
   <option value=".category2">category2</option>
   <option value=".category3">category3</option>
   ...
</select>

I'm not sure how the code has to be to achieve that structure, so far I have this which it's not working but at least it's not li's inside a ul anymore, it also just shows all of the categories twice, I need some kind of foreeach but that's beyond my knowledge:

             <?php $args = array(
                'hide_empty'         => 0,
                'orderby'            => 'name',
                'order'              => 'ASC',
                'show_count'         => 0,
                'use_desc_for_title' => 0,
                'title_li'           => 0,
                'style'              => '',
                'echo'               => false
              );
              $cats = wp_list_categories($args);

              if ( $cats ) {
                  echo '<option value=".'.$cats.'">'.$cats.'</option>'; 
          } ?> 
1

wp_list_categories() isn't the right function for this kind of output, as that is meant for displaying <ul> lists.

Instead you should be looking at get_categories(), that instead only gets all the info about the categories and doesn't apply any formatting to it.

For your desired output you can use something like this:

<?php
$args = array(
    'hide_empty' => 0,
    'orderby' => 'name',
    'order' => 'ASC',
);
$cats = get_categories($args);

if ( $cats ) {
    echo '<select class="filters-select">'; //echo the select

    //loop through each category and echo as option for the select
    foreach ($cats as $cat) { 
        echo '<option value="'. $cat->slug .'">'. $cat->cat_name .'</option>';
    }

    echo '</select>'; //close the select
}
?> 
  • Very nice, it works perfectly. – Sergi Oct 20 '17 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.