DEV Community

Rehmatullah Khan
Rehmatullah Khan

Posted on

How to Filter multiple Posts in WordPress by tag Using AJAX, without using any plugin

Step-1:
Html Checkbox Like this:

<div class="list">
<label for="arts" class="font">
   <input type="checkbox" class="subject-filter" name="subject[]" data - 
    taxonomy="worksheet-subject" value="arts" id="arts" />Arts
</label>
<label for="biology" class="font"
                  ><input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="biology" id="biology" />Biology</label>
<label for="chemistry" class="font">
<input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="chemistry" id="chemistry"/>
Chemistry</label>
<label for="bio" class="font">
<input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="grammar" id="grammar" />
Grammar</label>
<label for="lang" class="font">
<input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="language" id="language" />
Language</label>
<label for="arts" class="font">
<input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="maths" id="maths" />Maths</label>
</div>
Enter fullscreen mode Exit fullscreen mode

display all tabs or subjects container:

<!-- Container to display worksheets -->
<div class="worksheet-container">
<p>Select grades to view worksheets.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

Step-2:
create js file:

jQuery(document).ready(function ($) {
    // Fetch Subjects on any checkbox change
    $('.subject-filter').on('change', function () {
        // Gather all selected grades
        var taxonomy = $(this).data('taxonomy'); // Taxonomy name
        var terms = []; // Array to hold selected terms
        $('.subject-filter:checked').each(function () {
            terms.push($(this).val());
        });

        // Fetch Subjects for selected grades
        fetchSubjects(taxonomy, terms);
    });

    // Function to fetch Subjects
    function fetchSubjects(taxonomy = '', terms = []) {
        $.ajax({
            url: ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'fetch_subjects',
                nonce: ajax_object.nonce,
                taxonomy: taxonomy,
                terms: terms, // Send array of selected terms
            },
            beforeSend: function () {
                $('.worksheet-container').html('<p>Loading...</p>');
            },
            success: function (response) {
                if (response.success) {
                    $('.worksheet-container').html(response.data.html);
                } else {
                    $('.worksheet-container').html('<p>' + response.data.message + '</p>');
                }
            },
            error: function () {
                $('.worksheet-container').html('<p>An error occurred. Please try again.</p>');
            },
        });
    }
});

Enter fullscreen mode Exit fullscreen mode

Step-3:
Create Functions in functions.php:

// Register AJAX action for logged-in users (you can add for non-logged-in users too)
add_action('wp_ajax_fetch_subjects', 'fetch_subjects');
add_action('wp_ajax_nopriv_fetch_subjects', 'fetch_subjects');
function fetch_subjects() {
    // Verify nonce for security
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ajax_nonce')) {
        wp_send_json_error(array('message' => 'Nonce verification failed.'));
        wp_die();
    }

    // Get taxonomy and terms from the AJAX request
    $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : '';
    $terms = isset($_POST['terms']) ? array_map('sanitize_text_field', $_POST['terms']) : array();

    // Default query arguments
    $args = array(
        'post_type'      => 'worksheet',
        'posts_per_page' => -1, // Fetch all posts
    );

    // If terms are selected, modify the query
    if (!empty($taxonomy) && !empty($terms)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => $taxonomy,
                'field'    => 'slug',
                'terms'    => $terms, // Pass the array of selected terms
                'operator' => 'IN',   // Match any of the selected terms
            ),
        );
    }

    // Run WP_Query to fetch posts
    $query = new WP_Query($args);

    // Check if any posts were found
    if ($query->have_posts()) {
        $html = '';
        while ($query->have_posts()) {
            $query->the_post();
            // Output the post HTML
            $html .= '<div class="card">';
            $html .= '<div class="card-img">';
            // Add the post thumbnail
            if (has_post_thumbnail()) {
                $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'medium'); // Get the thumbnail URL
                $html .= '<img src="' . esc_url($thumbnail_url) . '" class="worksheets-card-img" alt="' . esc_attr(get_the_title()) . '" />';
            } else {
                $html .= '<img src="placeholder-image.jpg" class="worksheets-card-img" alt="Placeholder" />'; // Fallback for no thumbnail
            }
            $html .= '<div class="grade">';
            // Add the first category name or fallback
            $terms = get_the_terms(get_the_ID(), 'worksheet-grad');
            if ($terms && !is_wp_error($terms)) {
                foreach ($terms as $term) {
                    $html .= esc_html($term->name); // Display the first term name
                    break;
                }
            } else {
                $html .= 'No Grade Available'; // Fallback message
            } 

            $html .= '</div>';
            $html .= '<div class="age"> For Age 1-12</div>';            
            $html .= '</div>';            
            $html .= '<div class="card-content">';
            $html .= '<h2><a href="' . esc_url(get_permalink()) . '">' . get_the_title() . '</a></h2>';
            $html .= '<p>'. get_the_excerpt() .'</p>';
            $html .= '</div>';
            $html .= '</div>';
        }
        wp_send_json_success(array('html' => $html));
    } else {
        wp_send_json_error(array('message' => 'No worksheets found.'));
    }

    wp_die(); // Always terminate the request properly
}
`
**Step-4:**
enqueue scripts file using functions.php:
`
function enqueue_custom_scripts() {
    wp_enqueue_script('custom-ajax', get_template_directory_uri() . '/js/custom-ajax.js', array('jquery'), null, true);

    // Localize script to pass ajax_url and nonce to JS
    wp_localize_script('custom-ajax', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('ajax_nonce'),
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)