【问题标题】:wc_get_template_part not working with ajaxwc_get_template_part 不适用于 ajax
【发布时间】:2016-08-10 12:06:41
【问题描述】:

我正在尝试这个简单的 ajax 请求以通过 ajax 获取数据并使用 wc_get_template_part,但它返回 500 服务器错误。它卡在 content-product 页面的 to post_class() 上。

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

我做错了什么?

谢谢。

【问题讨论】:

  • 你好 loic 感谢您的回答,但我总是使用 exit 而不是死,我的 ajax 工作正常,但前几天 wc get template 部分无法正常工作,现在似乎工作正常...不知道为什么它不工作..虽然很奇怪..无论如何它现在可以工作,但感谢您的回答......
  • 非常感谢……这对我有帮助

标签: php ajax wordpress woocommerce product


【解决方案1】:

非常重要:为了避免错误 500:
总是在你的 php 函数末尾添加die();
(WordPress ajax)。

此外,您应该在 if/else 语句之外使用 wp_reset_query();wp_reset_postdata();

这是您重新访问的代码:

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

【讨论】:

    【解决方案2】:

    请使用wp_die(); 而不仅仅是die();

    【讨论】:

      猜你喜欢
      • 2013-08-30
      • 2015-07-04
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多