最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

search - How to load WP categories into array for autocomplete?

programmeradmin1浏览0评论

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)

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)

Share Improve this question asked May 6, 2019 at 13:15 DennisDennis 216 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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); ?>"];

发布评论

评论列表(0)

  1. 暂无评论