M é m o - l a b .
Ce chapitre explique comment intégrer ajax à WordPress par le biais d’un exemple précis : l’affichage d’articles.
Notions abordées : wp_register_script(), wp_localize_script(), wp_send_json(), add_action(‘wp_ajax_…), add_action(‘wp_ajax_nopriv…).
Rqe : Le traitement ajax se fait à l’aide de jquery, il faut donc charger jquery dans le fichier functions.php (se reporter au chapitre « Chargement des fichiers css et js« ).
template php
<?php
<div id="wrap_ajax_articles">
<button id="ajax_articles_btn">Articles</button>
// div d'affichage des articles
<div id="show_ajax_articles"></div>
</div>
?>
functions.php
<?php
// Chargement du fichier app.js auquel on passe une variable admin_ajax_url
// contenant l’url vers le fichier <projet>/wp-admin/admin-ajax.php.
// Cette url est récupérée à l’aide de la fonction admin_url('admin-ajax.php').
wp_register_script(
'app_js',
get_template_directory_uri() .'/dist/js/app.js',
['jquery'],
'1.0.0',
false
);
wp_localize_script('app_js', 'admin_ajax_url', admin_url('admin-ajax.php'));
wp_enqueue_script('app_js');
?>
<?php
function mytheme_ajax_articles() {
$articles = get_posts([
'type' => 'post',
'numberposts' => -1
]);
if (!empty($articles)) {
// $articles est un tableau d'objets
// La fonction renvoie ces données au format json
wp_send_json($articles);
}
die();
}
// action permettant d’appeler la fonction
// mytheme_ajax_articles() qui retourne la
// réponse à la requête ajax.
// pour utilisateurs non logués
add_action('wp_ajax_nopriv_do_show_ajax_articles', 'mytheme_ajax_articles');
// pour utilisateurs logués
add_action('wp_ajax_do_show_ajax_articles', 'mytheme_ajax_articles');
?>
app.js
jQuery(function($) {
$('#wrap_ajax_articles').on('click', '#ajax_articles_btn', function(e) {
e.preventDefault();
$.ajax({
type: 'get',
// Le paramètre url doit fournir l’url du fichier
// <projet>/wp-admin/admin-ajax.php.
// Cette url a été définie lors du chargement du fichier app.js
// et placée dans la variable admin_ajax_url.
url: admin_ajax_url,
data: {
// Sert à définir le nom des actions à lancer :
// 'wp_ajax_do_show_ajax_articles' et
// 'wp_ajax_nopriv_do_show_ajax_articles'
'action': 'do_show_ajax_articles'
},
// Le type de donnée attendu est du json
dataType: 'json',
// En cas de succès de la requête ajax, le résultat s’affiche
// dans la div contenant l’id #show_ajax_articles'
success: function(data, textStatus, jqXHR) {
// Affichage du résultat en html
$.each(data, function(i, v) {
$html = '<h3>' +v.post_title +'</h3>';
$html += '<p>' +v.post_content +'</p>';
$('#show_ajax_articles').append($html)
})
},
error: function(jqXHR, textStatus, errorThrown) {
$('#show_ajax_articles').text('erreur !!!')
}
})
})
});
Rqe : la fonction mytheme_ajax_articles() renvoie un tableau d’objets. Il est possible de faire en sorte que cette fonction renvoie directement un template. La fonction mytheme_ajax_articles() ainsi que le résultat retourné par la requête ajax doivent être modifiés comme suit :
Modification de la fonction mytheme_ajax_articles()
<?php
// <mytheme>/template-parts/ajax-articles.php
function mytheme_ajax_articles() {
$q = new WP_Query([
'post_type' => 'post'
]);
// La fonction renvoie du code html construit
// sur la boucle WP et le contenu du template
// <mytheme>/template-parts/ajax-articles.php
if ($q->have_posts()) : while ($q->have_posts()) : $q->the_post();
get_template_part('template-parts/ajax-articles');
endwhile; endif;
die();
}
?>
Création du template template ajax-articles.php
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
Modification du fichier app.js
jQuery(function($) {
...
// Le type de donnée attendu est du html
dataType: 'html',
success: function(data, textStatus, jqXHR) {
// Affichage du résultat en html
$('#show_ajax_articles').append(data)
}
....
});