I am currently making a new site and i am stuck with the autocomplete for the standard search form from wordpress. Anyone knows how can i load my wordpress categories to use in this script? Its a mix with javascript and php(to load my categories from wp)

enter image description here

enter image description here

enter image description here


It is not clear what autocomplete function you are using in JS, if it is from a library or custom, but I'm assuming that it expects an array where locations is passed and not a string, which is what you're feeding it.

The function you should be using is get_terms(), not wp_list_categories(), the former being used for returning an array of terms in a taxonomy, the latter is for returning a string of HTML markup. You can use the fields argument to filter which fields you want included in the results.

Example: $locations = get_terms( array( 'taxonomy' => 'category', 'hide_empty' => false, 'fields' => 'names' ) );

Secondly, as mentioned above, your locations variable is populated with a string in JS not an array. This might be fine if the autocomplete function were to parse it as JSON automatically, but in that case your string would not be valid JSON anyway as you are outputting a <ul> markup string inside the brackets. Try this:

var locations = ["<?php echo implode('", "', $locations); ?>"];

  • I tried your solution but in log it gives this now : [""] (empty i guess)
    – Dennis
    May 6 '19 at 14:18
  • Do you have any categories created in the default 'categories' taxonomy? Are you using a custom taxonomy?
    – KFish
    May 6 '19 at 14:44
  • Well i made custom post types and there i entered all my categories, they are the same for all cpt.
    – Dennis
    May 6 '19 at 14:50
  • Oh sorry, it should be 'cateogry' not 'categories' for the slug
    – KFish
    May 6 '19 at 14:51
  • As long as it's using the same built in 'category' taxonomy, it won't matter that it's on custom post types, this will give you all terms that exist in the 'category' taxonomy regardless of post type. Now if you used custom taxonomies to create custom category taxonomies then you would need to query by those custom taxonomy slugs.
    – KFish
    May 6 '19 at 14:54

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.