I have two files, alpine js and a ajax, i want to get my current post type from wordpress with
$post_type = get_post_type( $post->ID );
$postType = get_queried_object();
$args = array( 'post_type' => $post_type, 'post_status' => 'publish', );
and have that pass to my ajax so the post type that is filtered and default is depending on what post type i am currently on.
the code bellow is originally from this tutorial that i have been following, it works fine for a single post type but wish to inject the current post type into the ajax depending on post type.
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();