Reputation: 83
I'm trying this simple ajax request to get data via ajax and using wc_get_template_part
but it's returning the 500 server error. it stuck to post_class()
of content-product
page.
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');
What I am doing wrong?
Thanks.
Upvotes: 0
Views: 2450
Reputation: 254483
VERY IMPORTANT: To avoid the error 500:
always adddie();
at the end of your php function (WordPress ajax).
Also, you should use wp_reset_query();
with wp_reset_postdata();
outside your if/else statement.
Here is your revisited code:
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');
Upvotes: 1