Learn how to implement dynamic AJAX-based post filtering in WordPress. Fetch and display posts by taxonomy using radio buttons and checkboxes for seamless user interaction and improved functionality.
First, we cover the functionality of the radio button filter.
Step-1:
create js file and add this code:
jQuery(document).ready(function ($) {
// Fetch all worksheets by default when the page loads
fetchWorksheets();
// Trigger AJAX request when a grade filter is selected
$('.grade-filter').on('change', function () {
var taxonomy = $(this).data('taxonomy'); // e.g., 'worksheet-grad'
var term = $(this).val(); // Selected term slug
fetchWorksheets(taxonomy, term);
});
// Function to fetch worksheets
function fetchWorksheets(taxonomy = '', term = '') {
$.ajax({
url: ajax_object.ajax_url,
type: 'POST',
data: {
action: 'fetch_worksheets',
nonce: ajax_object.nonce,
taxonomy: taxonomy,
term: term,
},
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>');
},
});
}
});
Step-2:
add this code in functions.php file:
// Register AJAX action for logged-in users (you can add for non-logged-in users too)
add_action('wp_ajax_fetch_worksheets', 'fetch_worksheets');
add_action('wp_ajax_nopriv_fetch_worksheets', 'fetch_worksheets');
function fetch_worksheets() {
// 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 term from the AJAX request
$taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : '';
$term = isset($_POST['term']) ? sanitize_text_field($_POST['term']) : '';
// Default query arguments
$args = array(
'post_type' => 'worksheet',
'posts_per_page' => -1, // Fetch all posts
);
// If a specific term is selected, modify the query
if (!empty($taxonomy) && !empty($term)) {
$args['tax_query'] = array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term, // Fetch posts of the selected term
),
);
}
// 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 .= '<h3>' . get_the_title() . '</h3>';
$html .= '<div class="worksheet-excerpt">' . get_the_excerpt() . '</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-3:
add this code in functions.php for enque custom js file in wp.
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');
Step-4:
The html code structure add this on your template file.
<div class="grade">
<h2 class="filter-heading">GRADE</h2>
<ul>
<li>
<input type="radio" id="1st" name="radio" class="grade-filter" data-taxonomy="worksheet-grad" value="1st-grade" />
<label for="1st" class="font">1st Grade</label>
</li>
<li>
<input type="radio" id="2nd" name="radio" class="grade-filter" data-taxonomy="worksheet-grad" value="2nd-grade" />
<label for="2nd" class="font">2nd Grade</label>
</li>
</ul>
</div>
Note: please the css class on radio button change according your css class and data-taxonomy="worksheet-grad" alsoe. second important point is the value="2nd-grade" is change to your category slug.
Top comments (0)