最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

AJAX - get_posts for a specific post type returns empty

programmeradmin1浏览0评论

I'm trying to load more posts via an ajax call but the array always returns empty.

To troubleshoot, I replaced the "testimonial" in "get_posts" with "post" and "application" (another custom post type) and both worked fine.

At the same time, when I test the same "get_posts" function directly on the page and print_r the result, it returns the testimonials as it should. But when the same function is performed via ajax, it comes back empty.

I'm totally lost how to solve it and will be gratefull for any suggestion.

jQuery part:

        var showMoreBtn = $('#show_more');

        showMoreBtn.on('click', function(e) {
            e.preventDefault();
            var data = {
                action: 'ajax_show_more_testims',   
                max: <?php echo $max; ?>,
                security: '<?php echo wp_create_nonce("show-more"); ?>',
            }

            $.post(ajaxurl, data, function(response) {
                var responseData = JSON.parse(response);
                console.log(responseData);
            });
        });

AJAX:

add_action('wp_ajax_ajax_show_more_testims', 'ajax_show_more_testims');
add_action('wp_ajax_nopriv_ajax_show_more_testims', 'ajax_show_more_testims');

function ajax_show_more_testims() {
    check_ajax_referer('show-more', 'security');

    $max = (int) $_POST['max'];

    $testims = get_posts(array(
        'numberposts' => -1,
        'post_type' => 'testimonial',
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC',
    ));

    echo json_encode($testims);

    wp_die();
}```
发布评论

评论列表(0)

  1. 暂无评论