Creating multilingual glossary for WP
I'm trying to create multilingual glossary using WP WPML custom post type. And I found solution to achieve this. Link to the page example - link
1) Added to functions.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' );
alphabet.js file contains this script:
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');
};
});
})
});
Then I have added this to functions.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');
And my page template contains this code:
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
And when I debug this page (click on any letter) I see the error in console
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Where I was mistaken? Thanks in advance)
Topic plugin-qtranslate plugin-wpml pagination Wordpress
Category Web