admin管理员组

文章数量:1125572

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();

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();
Share Improve this question edited Feb 12, 2024 at 12:58 Beep asked Feb 10, 2024 at 0:36 BeepBeep 297 bronze badges 3
  • 1 yeah, just read though. will update so its clear. apologies – Beep Commented Feb 12, 2024 at 12:54
  • Do you mean you need to get data for all custom post types? – Pratik bhatt Commented Feb 14, 2024 at 11:14
  • Feel free to post your own solution too! – Rup Commented Feb 14, 2024 at 16:25
Add a comment  | 

2 Answers 2

Reset to default 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();
}

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();

本文标签: Post current post type to my Ajax