未捕获的类型错误:从 wp 检索标签时无法读取 null 的属性“长度”
2018-07-14
1213
我正在尝试使用 jquery 自动完成功能从
wordpress db
中检索标签
首先,我在 wp 中设置了一个函数:
if ( ! function_exists( 'yourtheme_frontend_scripts' ) ) {
function yourtheme_frontend_scripts() {
wp_enqueue_script( 'yourtheme_custom', get_template_directory_uri().'/js/tags.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
) );
}
}
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' );
}
}
然后我创建一个 js:
$(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 ) );
}) );
}
});
});
最后我输入:
<input class="form-control" id="tags">
但是,当我开始输入时,我得到了:
Uncaught TypeError: Cannot read property 'length' of null
和
at a.(EXAMPLE PATH/anonymous function).(anonymous function).source
2个回答
如果您正在使用 Divi,那么可能是文件链接的问题。链接您已选择为操作设置的每个文件。
Rahul Sharma
2018-07-15
这是我解决它的方法:
在 php 函数中,我运行 ajax 来循环我的类别列表并检查用户输入的内容是否存在,否则我让他自己写:
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
var dataArray = data.split("|");
jQuery( "#keyword" ).autocomplete({
source: dataArray
});
}
});
}
</script>
<?php
}
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$key = $_POST['keyword'];
$args = array(
'orderby' => 'id',
'hide_empty'=> 0,
'name__like' => $key
);
$categories = get_categories($args);
foreach ($categories as $cat) {
echo $cat->name."|";
}
die();
}
然后我使用 jquery 自动完成设置输入:
<div class="ui-widget">
<label for="keyword">Tags: </label>
<input id="keyword" onkeyup="fetch()">
</div>
注意:
我们需要在 wp 函数中加载自动完成和 css:
function add_scripts(){
wp_enqueue_script( 'jquery-ui-autocomplete' );
}
add_action('wp_enqueue_scripts', 'add_scripts');
function add_stylesheet_to_head() {
echo "<link href='https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.css' rel='stylesheet' type='text/css'>";
}
rob.m
2018-07-15