tonik / theme

Tonik is a WordPress Starter Theme which aims to modernize, organize and enhance some aspects of WordPress theme development.
http://labs.tonik.pl/theme/
MIT License
1.33k stars 140 forks source link

在ajaxes.php文件请求数据时,使用new WP_Query,会显示错误500,谢谢。 #103

Closed Evllis closed 3 years ago

Evllis commented 3 years ago

js代码:

$.ajax({
    url: global.ajaxurl,
    type: 'POST',
    dataType: 'html',
    data: {
        paged: 1,
        tabcid: 14,
        action: 'ajax_load_posts'
    }
})
    .done(response => {
        console.log('======================')
        console.log(2222, response)
        console.log('======================')
    })
    .always(() => {
        $('div.card-skeleton').detach()
        $('.ajax-loading').hide()
    });

下面代码的文件在:site/app/Http/ajaxes.php

add_action('wp_ajax_ajax_load_posts', 'Tonik\Theme\App\Http\ajax_load_posts_callback');
add_action('wp_ajax_nopriv_ajax_load_posts', 'Tonik\Theme\App\Http\ajax_load_posts_callback');
function ajax_load_posts_callback() {

    $paged = isset( $_POST['paged'] ) ? $_POST['paged'] : '';
    $tabcid = isset( $_POST['tabcid'] ) ? $_POST['tabcid'] : '';

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 8,
        'order' => 'DESC',
        'ignore_sticky_posts' => 1,
        'cat' => $tabcid,
        'paged' => $paged
    );

    $the_query = new WP_Query($args);

    echo wp_send_json(array(
        'code' => 400,
        'msg' => $the_query
    ));
    die;

    if ($the_query -> have_posts()):
        while ($the_query -> have_posts()): $the_query -> the_post(); ?>
            <div>2222</div>
        <?php endwhile;

    else:
        // echo 'No posts found';
    endif;
    //wp_reset_postdata();
    //header('Content-Type: application/json; charset=utf-8');
    //header('Cache-Control: no-cache, must-revalidate');
    //header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    //echo json_encode($arr);
    die();
}

当我把事件处理函数放在Tonik\Theme\App\Http\里面后,执行new WP_Query后,就会500错误。

1

====================================

如果我把上面的代码放在function.php文件里,则可以正常访问,请问是怎么回事?

add_action('wp_ajax_ajax_load_posts', 'ajax_load_posts');
add_action('wp_ajax_nopriv_ajax_load_posts', 'ajax_load_posts');

2

是因为获取不到WP_Query构造函数吗?

Evllis commented 3 years ago

没事了,我刚才找到问题所在了。 我在app/Http/ajaxes.php文件里的最上面,添加了WP_Query的命名空间。 现在可以正常使用了。刚才是因为我没有细查代码,缺少use的使用。抱歉。

3