0

I have made a AJAX Filter with Wordpress, but my loop is not working. Who can help me with this?

I try to get custom fields back that i use with ACF.

 function filter_reports() {
   global $customer_account;
   $args = array(
     'post_type' => 'ebooks',
     'tax_query' => array(
       'relation' => 'AND',
       array(
         'taxonomy' => 'customer',
         'field'    => 'term_id',
         'terms'    => $customer_account,
       ),
       array(
         'taxonomy' => 'disease',
         'field'    => 'term_id',
         'terms'    => $_POST['options'],
       )
     ),
   );



$the_query = new WP_Query( $args );
$results = array();

   if ( $the_query->have_posts() ) {
     while ( $the_query->have_posts() ) {
    $id =  get_the_ID();
      array_push($results, array(
        'id' => $id,
        'title' => get_field('title', $id),
        'chair' => get_field('e-chair', $id),
      ));
    }
  }

  echo json_encode($results);
  die;

}
  add_action( 'wp_ajax_filter_reports', 'filter_reports' );
4
  • two things, ajax should return things not echo you are not echo array for God's sake , and you are missing wp_ajax_nopriv_... probable.
    – prosti
    Jan 16, 2017 at 10:20
  • So what should i do? I am learning.
    – Dionoh
    Jan 16, 2017 at 10:21
  • Writing you a reply...
    – prosti
    Jan 16, 2017 at 10:22
  • 1
    Please consider my answer, as most helpful for now, since no other replies.
    – prosti
    Jan 16, 2017 at 10:32

1 Answer 1

0

I think you should organize your code to return things from Ajax call. If this should work for any user you need to use also wp_ajax_nopriv_...

However, I would use dionoh_filter_reports action name.

add_action( 'wp_ajax_dionoh_filter_reports', 'filter_reports' );
add_action( 'wp_ajax_nopriv_dionoh_filter_reports', 'filter_reports' );

I suggest you check this and learn more.

3
  • I still get an 500 error.
    – Dionoh
    Jan 16, 2017 at 10:33
  • There is something going on within my loop i think.
    – Dionoh
    Jan 16, 2017 at 10:33
  • 1
    Please narrow down your problems and ask the new question. I already provided you few tips to improve your Ajax skills in WordPress. Be fair and report all things you get such as error 500 in the new question.
    – prosti
    Jan 16, 2017 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.