skip to Main Content

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);
            },
        });
    }
});
`

2

Answers


  1. Chosen as BEST ANSWER

    Thank you, Elinor. I've changed my method and put a script into a folder "js" in my child theme and called it 'filterable-gallery.js' and I'm trying to enqueue it in functions.php with this code but the script is not executed ... I'm missing something

    functions.php

    function theme_enqueue_scripts() {
        // Enqueue jQuery
        wp_enqueue_script('jquery');
    
        // Enqueue ajax
        wp_enqueue_script( 'filterable-gallery-script', get_stylesheet_directory_uri() . '/js/filterable-gallery.js', array('jquery'), null, true );
        wp_localize_script( 'filterable-gallery-script', 'filterable_gallery_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
    }
    
    add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
    

    filterable-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;
            }
    
            console.log(categoryClicked);
    
            // Utilisation de jQuery pour simplifier la requĂȘte AJAX
            $.ajax({
                type: 'POST',
                url: filterable-gallery_object.ajaxurl,
                dataType: 'html',
                data: { 
                    action: 'filterable_gallery_action',
                    category: categoryClicked,
                    nonce: filterable_gallery_obj.nonce
                },
                success: (response) => {
                    console.log(response);
                },
            });
        }
    });
    

  2. Take a look on this post.
    I think you missed one step : ajax routing in WordPress.
    Good luck!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search