我正在尝试使用WP&;创建多语言词汇表;WPML和;自定义帖子类型。我找到了实现这一目标的解决方案。链接到页面示例-link
1) 添加到函数。php
function get_ajax_url() {
if (is_page(array(2017,2021,2023,2027))) {
wp_enqueue_script( \'ajax-script\', get_template_directory_uri() . \'/js/alphabet.js\', array(\'jquery\') );
wp_localize_script( \'ajax-script\', \'my_ajax_object\',
array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );
}
}
add_action( \'wp_enqueue_scripts\', \'get_ajax_url\' );
字母表。js文件包含以下脚本:
jQuery(document).ready(function($)
{
jQuery(\'.alphabet\').click(function(){
var data = {
action: \'get_by_char\',
char: this.id
};
jQuery.post(my_ajax_object.ajaxurl, data, function(response) {
$("#abc-drugs").html(\'\');
$.each($.parseJSON(response), function() {
var they = this;
$("#abc-drugs").append
(
\'<li class="drug">\' +
\'<a href="\' + they.url + \'">\' +
\'<h2 class="md7_drug_title">\' + they.title + \'</h2>\' +
\'</a>\' +
\'</li>\'
);
});
if(response.length < 3){
$("#abc-drugs").html(\'<div class="no-drug-array">Препаратов не найдено</div>\');
};
});
})
});
然后我将其添加到函数中。php
function get_by_char_callback()
{
global $wpdb;
$b=array();
$char=$_POST[\'char\'];
$a=$wpdb->get_results(\'SELECT post_title,ID FROM wpwv_posts where post_type="drug" and post_status="publish" and (post_title like "[:ru]\'.$char.\'%" or post_title like "%[:en]\'.$char.\'%" or post_title like "\'.$char.\'%") \',ARRAY_A );
foreach ($a as $key => $value)
{
$b[$key][\'title\']=translate($value[\'post_title\']);
}
echo json_encode($b);
wp_die();
}
add_action(\'wp_ajax_get_by_char\', \'get_by_char_callback\');
add_action(\'wp_ajax_nopriv_get_by_char\', \'get_by_char_callback\');
“我的页面”模板包含以下代码:
<div class="alphabet-wrap">
<?php
$alphabet=array(
\'ru_RU\'=>array(\'а\',\'б\',\'в\',\'г\',\'д\',\'е\',\'ё\',\'ж\',\'з\',\'и\',\'й\',\'к\',\'л\',\'м\',\'н\',\'о\',\'п\',\'р\',\'с\',\'т\',\'у\',\'ф\',\'х\',\'ц\',\'ч\',\'ш\',\'щ\',\'э\',\'ю\',\'я\'),
\'en_US\'=>array(\'a\',\'b\',\'c\',\'d\',\'e\',\'f\',\'g\',\'h\',\'i\',\'j\',\'k\',\'l\',\'m\',\'n\',\'o\',\'p\',\'q\',\'r\',\'s\',\'t\',\'u\',\'v\',\'w\',\'x\',\'y\',\'z\'),
\'de_DE\'=>array(\'a\',\'ä\',\'b\',\'c\',\'d\',\'e\',\'f\',\'g\',\'h\',\'i\',\'j\',\'k\',\'l\',\'m\',\'n\',\'o\',\'ö\',\'p\',\'q\',\'r\',\'s\',\'ß\',\'t\',\'u\',\'ü\',\'v\',\'w\',\'x\',\'y\',\'z\'),
);
foreach ($alphabet[get_locale()] as $key => $value):
?>
<span id="<?=$value?>" class="alphabet"><?=$value?></span>
<?php endforeach;?>
</div>
<ul class="drugs" id="abc-drugs">
<?php $args = array(
\'post_type\' => \'drug\',
\'posts_per_page\' => -1
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php the_permalink() ?>"><?php the_title() ?></a>
<?php endwhile;
} else {
echo __( \'Препаратов не найдено\' );
}
wp_reset_postdata();
?>
</ul>
当我调试这个页面时(单击任何字母),我在控制台中看到了错误
语法错误:JSON。parse:JSON数据的第1行第1列出现意外字符
我错在哪里?提前感谢)