I have alpine.js making a api call from Ajax.
In my Ajax I need to have the post type update depending on the current post type, I can set this is a php file.
I would like to get the current post type with wp php
$post_type = get_post_type( $post->ID );
$postType = get_queried_object();
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
);
then pass into my javascript and have that post type known with the ajax so no matter what post type i have the ajax and js know.
**js
**
import Alpine from 'alpinejs'
Alpine.data("filterPosts", (adminURL) => ({
posts: "",
limit: 10,
category: null,
showDefault: true,
showFiltered: false,
filterPosts(id) {
this.showDefault = false;
this.showFiltered = true;
this.category = id;
this.fetchPosts();
},
fetchPosts() {
var formData = new FormData();
formData.append("action", "filterPosts");
formData.append("offset", this.offset);
formData.append("limit", this.limit);
if (this.category) {
formData.append("category", this.category);
}
fetch(adminURL, {
method: "POST",
body: formData,
})
.then((res) => res.json())
.then((res) => {
this.posts = res.posts;
});
}
}));
window.Alpine = Alpine
Alpine.start()
Ajax
?php
// the ajax function
add_action('wp_ajax_filterPosts', 'filterPosts');
add_action('wp_ajax_nopriv_filterPosts', 'filterPosts');
function filterPosts()
{
$response = [
'posts' => "",
];
$filter_args = array(
'post_status' => 'publish',
'post_type' => 'post'
);
if ($_POST['limit']) {
$filter_args['posts_per_page'] = $_POST['limit'];
}
if ($_POST['category']) {
$filter_args['cat'] = $_POST['category'];
}
$filter_query = new WP_Query($filter_args);
if ($filter_query->have_posts()) :
while ($filter_query->have_posts()) : $filter_query->the_post();
$response['posts'] .= load_template_part('/template-parts/posts-filter/single-post');
endwhile;
wp_reset_postdata();
endif;
echo json_encode($response);
die();