我为WordPress类别构建了一个自动完成的搜索框(实际上是一个自定义分类法),它非常有效(即键入时显示类别)。但是,当键入1个键时,它将显示所有结果,而不管该字符串是否匹配任何类别。
下面是我的PHP代码(autocomplete.PHP,在我的主题目录的根目录中):
<?php
include_once($_SERVER[\'DOCUMENT_ROOT\'].\'/wp-load.php\' ); // I know the traditional way to do it is loading admin_ajax but I read this was exactly the same and didn\'t increase the overhead to the server
if (isset($_GET[\'term\'])) { // I suspect the problem is something to with this
$tradeList = get_terms(\'trade\');
$tradeNames = Array();
foreach ($tradeList as $trade) {
$tradeName = $trade->name;
array_push($tradeNames, $tradeName);
}
echo json_encode($tradeNames);
}
?>
和我的Javascript代码:$(document).ready(function() {
$(".main-search-field").autocomplete({
source: "/wp-content/themes/local_directory/autocomplete.php",
minLength: 1
});
});
最后是HTML:<input type="text" class="main-search-field" name="search" id="search">
我意识到这可能是错误的编码,如果可以重新做的话。但我真正需要知道的是如何获得与搜索框中键入的字符串相关的自动完成建议。感谢您的帮助:)