I'm using WordPress, and I'm trying to learn how to create a filterable gallery on my own using ajax. To achieve this, I've created a page with a template called filterable-gallery-template.php. The file is located in my child theme. In my page, I've added a JavaScript snippet using wpcode and calling it with a shortcode.
What I'm attempting to do is to obtain the category value when a button is clicked, send this value to my PHP template, and then filter my gallery (I've added categories for my images using a plugin). However, I'm facing a 500 error. I've tried to retrieve the value of var_dump($category), and I have succeeded in getting the category name only once when visiting the page for the first time. After that, the buttons don't work, and I don't see any images. Here is my code, thanks in advance for your help :)
filterable-gallery-template.php
`<?php
/* Template Name: filterable Gallery */
?>
<nav class="filterable-gallery">
<ul>
<li><a class="wp-block-button__link filterable-gallery__btn on">Print</a></li>
<li><a class="wp-block-button__link filterable-gallery__btn">Webdesign</a></li>
<li><a class="wp-block-button__link filterable-gallery__btn">Branding</a></li>
<li><a class="wp-block-button__link filterable-gallery__btn">Illustration</a></li>
</ul>
</nav>
<div class="gallery">
<?php
$category = isset($_POST['category']) ? $_POST['category'] : 'Print';
echo '<pre>';
var_dump($category);
echo '</pre>';
$args = array(
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
'post_mime_type' => 'image',
'post_parent' => get_the_ID(),
'post_status' => null,
'post_type' => 'attachment',
'tax_query' => array(
array(
'taxonomy' => 'attachment_tag',
'field' => 'slug',
'terms' => $category,
),
),
);
$images = get_posts($args);
if ($images) {
foreach ($images as $image) {
$image_id = $image->ID;
$title = get_the_title($image_id);
?>
<div class="gallery-item">
<img src="<?php echo wp_get_attachment_url($image_id); ?>" alt=""/>
<div class="overlay">
<h5><?php echo $title; ?></h5>
</div>
</div>
<?php
}
} else {
echo '<p>Aucune image trouvée avec la catégorie "' . esc_html($category) . '".</p>';
}
?>
</div>
`
Javascript snippet
`jQuery(document).ready(function($) {
let isActive = document.getElementsByClassName('on');
let buttons = document.getElementsByClassName('filterable-gallery__btn');
for (let buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
buttons[buttonIndex].addEventListener('click', function(event) {
activer(event);
});
}
function activer(e) {
let categoryClicked = null;
if (!e.target.classList.contains('on')) {
for (let i = 0; i < isActive.length; i++) {
isActive[i].classList.remove('on');
}
e.target.classList.add('on');
categoryClicked = e.target.innerText.toLowerCase();
} else {
return;
}
console.log(categoryClicked);
// Utilisation de jQuery pour simplifier la requête AJAX
$.ajax({
type: 'POST',
url: '/wp-content/themes/twentytwentyone-child/filterable-gallery-template.php',
dataType: 'html',
data: {category: categoryClicked },
success: function(response) {
console.log(response);
},
});
}
});
`
Take a look on this post. I think you missed one step : ajax routing in WordPress. Good luck!
February 4, 2024
Thank you, Elinor. I've changed my method but I still have problems, here is my code updated. Please what i'm missing, can somebody help me to understand ?
functions.php
function theme_enqueue_scripts() {
// Enqueue jQuery
wp_enqueue_script('jquery');
// Enqueue le script
wp_enqueue_script('filterable-gallery-script', get_stylesheet_directory_uri() . '/js/filterable-gallery.js', array('jquery'), null, true);
// Localisez le script avec la variable filterable_gallery_object
wp_localize_script(
'filterable-gallery-script',
'filterable_gallery_object',
array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('filterable_gallery_nonce')
)
);
}
add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
// Ajouter le support de l'API AJAX dans WordPress
add_action('wp_ajax_filterable_gallery_action_callback', 'filterable_gallery_action_callback');
add_action('wp_ajax_nopriv_filterable_gallery_action_callback', 'filterable_gallery_action_callback');
function filterable_gallery_action_callback() {
check_ajax_referer('filterable_gallery_nonce', 'nonce');
$category = isset($_POST['category']) ? sanitize_text_field($_POST['category']) : 'Print';
try {
$args = array(
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
'post_mime_type' => 'image',
'post_parent' => get_the_ID(),
'post_status' => null,
'post_type' => 'attachment',
'tax_query' => array(
array(
'taxonomy' => 'attachment_tag',
'field' => 'slug',
'terms' => $category,
),
),
);
$images = get_posts($args);
$gallery_html = '';
if ($images) {
foreach ($images as $image) {
$image_id = $image->ID;
$title = get_the_title($image_id);
$gallery_html .= '<div class="gallery-item"><img src="' . esc_url(wp_get_attachment_url($image_id)) . '" alt=""/><div class="overlay"><h5>' . esc_html($title) . '</h5></div></div>';
}
} else {
$gallery_html = '<p>Aucune image trouvée avec la catégorie "' . esc_html($category) . '".</p>';
}
wp_send_json_success(array('category' => $category, 'images' => $gallery_html));
} catch (Exception $e) {
error_log('Error in filterable_gallery_action_callback: ' . $e->getMessage());
wp_send_json_error(array('message' => 'Une erreur s\'est produite lors du traitement de la requête AJAX.'));
}
wp_die();
}
js/template-gallery.js
jQuery(document).ready(function($) {
console.log('yes');
let isActive = document.getElementsByClassName('on');
let buttons = document.getElementsByClassName('filterable-gallery__btn');
for (let buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
buttons[buttonIndex].addEventListener('click', (event) => {
activer(event);
});
}
function activer(e) {
let categoryClicked = null;
if (!e.target.classList.contains('on')) {
for (let i = 0; i < isActive.length; i++) {
isActive[i].classList.remove('on');
}
e.target.classList.add('on');
categoryClicked = e.target.innerText.toLowerCase();
} else {
return;
}
jQuery.ajax({
type: 'POST',
url: filterable_gallery_object.ajaxurl,
data: {
action: 'filterable_gallery_action',
category: categoryClicked,
nonce: filterable_gallery_obj.nonce
},
success: (response) => {
console.log('Category:', response.category);
console.log('Images:', response.images);
},
error: (error) => {
console.error(error);
},
});
}
});
filterable-gallery-template.php
<?php
/* Template Name: Filterable Gallery */
?>
<nav class="filterable-gallery">
<ul>
<li><a class="wp-block-button__link filterable-gallery__btn on">Print</a></li>
<li><a class="wp-block-button__link filterable-gallery__btn">Webdesign</a></li>
<li><a class="wp-block-button__link filterable-gallery__btn">Branding</a></li>
<li><a class="wp-block-button__link filterable-gallery__btn">Illustration</a></li>
</ul>
</nav>
<div class="gallery">
<?php
// La logique de récupération des images est gérée via AJAX
?>
</div>
February 4, 2024
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand
February 4, 2024
February 4, 2024