2016-08-10 150 views
0

我想這個簡單的Ajax請求通過AJAX獲取數據,並使用wc_get_template_part但它返回500服務器錯誤工作。它卡住to post_class()content-product頁面。wc_get_template_part不與阿賈克斯

function shop_filter(){ 
    if (! isset($_POST['shop_filter_nonce']) || ! wp_verify_nonce($_POST['shop_filter_nonce'], 'shop_filter_nonce')) 
     return; 
    $args=array('post_type'=>'product','order'=>'desc','posts_per_page'=>-1); 
    $loop = new WP_Query($args); 
    if ($loop->have_posts()){ 
     while($loop->have_posts()): $loop->the_post(); 
      wc_get_template_part('content', 'product'); 
     endwhile; 
     wp_reset_query(); 
    } 
    else 
    { 
     get_template_part('template-parts/content','none'); 
    } 
} 
add_action('wp_ajax_shop_filter','shop_filter'); 
add_action('wp_ajax_nopriv_shop_filter','shop_filter'); 

我在做什麼錯了?

謝謝。

+0

你好LOIC感謝您的回答,但我總是用出口而不是死了,我的AJAX工作正常,但一些如何該wc得到模板的一部分是沒有工作的前一天,現在它似乎工作正常...不知道爲什麼它不工作..雖然雖然很多,但它的工作現在,並感謝您的答案,但... –

+0

謝謝你非常......這對我有幫助 – LoicTheAztec

回答

1

非常重要:要避免錯誤500:
總是在你的PHP函數
(WordPress的AJAX)的末尾添加die();

此外,你應該使用wp_reset_query();wp_reset_postdata();你的if/else語句之外。

這是你重新審視代碼:

function shop_filter(){ 
    if (! isset($_POST['shop_filter_nonce']) || ! wp_verify_nonce($_POST['shop_filter_nonce'], 'shop_filter_nonce')) 
     return; 
    $args=array('post_type'=>'product','order'=>'desc','posts_per_page'=>-1); 
    $loop = new WP_Query($args); 
    if ($loop->have_posts()){ 
     while($loop->have_posts()): $loop->the_post(); 
      wc_get_template_part('content', 'product'); 
     endwhile; 
    } 
    else 
    { 
     get_template_part('template-parts/content','none'); 
    } 
    // Optionally (if needed). 
    wp_reset_query(); 
    wp_reset_postdata(); 

    // To avoid error 500 (don't forget this) 
    die(); 
} 
add_action('wp_ajax_shop_filter','shop_filter'); 
add_action('wp_ajax_nopriv_shop_filter','shop_filter'); 
0

請使用wp_die();,而不是隻是die();