1

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();
3
  • 1
    yeah, just read though. will update so its clear. apologies
    – Beep
    Commented Feb 12 at 12:54
  • Do you mean you need to get data for all custom post types? Commented Feb 14 at 11:14
  • Feel free to post your own solution too!
    – Rup
    Commented Feb 14 at 16:25

2 Answers 2

1
+100

To pass the current post type to your AJAX request, you need to modify your JS to include the post type information in the AJAX request. You can achieve this by adding the post type as a parameter when calling the filterPosts() function

JS

import Alpine from 'alpinejs';

Alpine.data("filterPosts", (adminURL, postType) => ({
    posts: "",
    limit: 10,
    category: null,
    showDefault: true,
    showFiltered: false,

    filterPosts(id) {
        this.showDefault = false;
        this.showFiltered = true;
        this.category = id;
        this.fetchPosts(postType); // Pass post type to fetchPosts function
    },

    fetchPosts(postType) { // Add postType parameter
        var formData = new FormData();
        formData.append("action", "filterPosts");
        formData.append("offset", this.offset);
        formData.append("limit", this.limit);
        formData.append("post_type", postType); // Include post type in form data

        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

// 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' => isset($_POST['post_type']) ? $_POST['post_type'] : 'post', // Use the post type received from AJAX request
    );

    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();
}
4
  • solved it a few days back myself, but this is very close to how i solved it so accepting this answer.
    – Beep
    Commented Feb 14 at 12:20
  • Where do you get the post type value on the page though? I thought that was part of the problem.
    – Rup
    Commented Feb 14 at 16:25
  • I actually get it from the dom using js
    – Beep
    Commented Feb 14 at 16:48
  • 1
    @Rup I use JS to get it from the dom, then load into my php, when im free will update my question with the solution I have
    – Beep
    Commented Feb 14 at 16:49
1

Hi please replace your ajax function like this

    function filterPosts()
{
    $show_post_types = get_post_types();
    $post_type_array = array();

  foreach ($show_post_types  as $pt) {
    array_push($post_type_array, $pt);

  }
    $response = [
        'posts' => "",
    ];

    $filter_args = array(
        'post_status' => 'publish',
        'post_type' =>  $post_type_array
    );

    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();
3
  • I don't think that solves it? That would load all post types, not just the one matching the current page
    – Rup
    Commented Feb 14 at 16:22
  • (unless I'm misreading your change: can you explain what you have changed please?)
    – Rup
    Commented Feb 14 at 16:22
  • Yes this is suppose to load all post types. I misunderstood the question. Commented Feb 16 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.