filter by category code Ajex

<select id="category_select">
<option value="">Select Category</option>
<?php
$categories = get_categories();
foreach ($categories as $category) {
echo '<option value="' . $category->cat_ID . '">' . $category->name . '</option>';
}
?>
</select>
<?php
// Add AJAX action for authenticated users
add_action('wp_ajax_filter_posts_by_category', 'filter_posts_by_category_callback');

// Add AJAX action for non-authenticated users
add_action('wp_ajax_nopriv_filter_posts_by_category', 'filter_posts_by_category_callback');

function filter_posts_by_category_callback() {
$category_id = intval($_POST['category_id']);

$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'cat' => $category_id // Filter posts by category ID
);

$posts = get_posts($args);

$response = array();

foreach ($posts as $post) {
$response[] = array(
'title' => $post->post_title,
'content' => $post->post_content
);
}

wp_send_json($response);
}
?>


<script type="text/javascript">
jQuery(document).ready(function($) {
$('#category_select').change(function() {
var category_id = $(this).val();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'filter_posts_by_category',
category_id: category_id
},
success: function(response) {
$('#posts_container').empty(); // Clear previous posts

if (response) {
response.forEach(function(post) {
$('#posts_container').append('<div class="post"><h2>' + post.title + '</h2><p>' + post.content + '</p></div>');
console.log(post);
});
} else {
$('#posts_container').html('<p>No posts found</p>');
}
},
error: function(xhr, status, error) {
console.error('AJAX Error:', error);
}
});
});
});

</script>

Leave a comment