我正在尝试使用PHP脚本在wordpress网站上设置自动完成功能。 但是我的代码中当前没有显示任何内容。我知道一般的想法是有一个jQuery函数,该函数将使用PHP脚本,在这种情况下可以提取MySQL数据(suggest.php)。另外,如果我要把
<script>
$( function() {
$( "#tags" ).autocomplete({
source: 'suggest.php',
minLength:1
});
} );
</script>
在 myScript 中.js在 js 文件夹下,我将如何访问它?我的完整代码如下...
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>
$( function() {
$( "#tags" ).autocomplete({
source: 'suggest.php',
minLength:1
});
} );
</script>
<form action="" method="post">
Name: <input type="text" name="tags" id="tags" value="<?php echo isset($_POST['tags']) ? $_POST['tags'] : '' ?>"/>
</form>
首先,不要包括整个jquery-ui
,这是完全没有必要的。
其次,不要手动放置脚本。这就是WordPress排队的原因。
首先,您需要将脚本排队到自动完成的位置,并且它必须依赖于自动完成。所以在你的functions.php
你会把
add_action( 'after_setup_theme', 'yourtheme_theme_setup' );
if ( ! function_exists( 'yourtheme_theme_setup' ) ) {
function yourtheme_theme_setup() {
add_action( 'wp_enqueue_scripts', 'yourtheme_frontend_scripts' );
}
}
if ( ! function_exists( 'yourtheme_frontend_scripts' ) ) {
function yourtheme_frontend_scripts() {
wp_enqueue_script( 'yourtheme_custom', get_template_directory_uri().'/js/custom.js', array( 'jquery-ui-autocomplete', 'jquery' ), '1.0.0', true );
wp_localize_script( 'yourtheme_custom', 'yourtheme_autocomplete', array(
'autocomplete' => json_encode($results_array), // Results array contains all your autocomplete words
) );
}
}
如何调用.js
文件取决于您。我称它为custom.js
并将其放在主题的/js 文件夹中。
您还需要一个 $results_array
,在此处包含所有自动完成的单词。我通常手动放置它们,或者在需要时查询数据库。
然后在你的custom.js
中,你会放这样的东西:
jQuery(document).ready(function($) {
"use strict";
var autocomplete_terms = JSON.parse( yourtheme_autocomplete.autocomplete );
$('#tags').autocomplete({
source: autocomplete_terms,
minLength: 1
});
});
应该工作正常。一个很酷的补充是,如果您有重音或拉丁语扩展术语,请将它们添加到重音符号地图中
jQuery(document).ready(function($) {
"use strict";
var autocomplete_terms = JSON.parse( yourtheme_autocomplete.autocomplete );
var accentMap = {
"ä": "a",
"ö": "o",
"å": "a",
"č": "c"
};
var normalize = function( term ) {
var ret = "";
for ( var i = 0; i < term.length; i++ ) {
ret += accentMap[ term.charAt(i) ] || term.charAt(i);
}
return ret;
};
$('#tags').autocomplete({
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( autocomplete_terms, function( value ) {
value = value.label || value.value || value;
return matcher.test( value ) || matcher.test( normalize( value ) );
}) );
}
});
});
希望这有帮助。