Advertisement
DidouS

how to get AJAX return something

Jun 13th, 2020
839
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.35 KB | None | 0 0
  1. /**
  2.  * adds the ability to use the following url to get something
  3.  *
  4.  * https://www.domainname.com/wp-admin/admin-ajax.php?action=all_questions
  5.  *
  6.  * notice that we add it twice: the first is for logged in users, the second one for non-logged in users, so without privileges
  7.  *
  8.  */
  9. add_action( 'wp_ajax_all_questions' , 'get_all_questions' );
  10. add_action( 'wp_ajax_nopriv_all_questions' , 'get_all_questions' );
  11.  
  12.  
  13. /**
  14.  * Get all posts from a CPT called 'questions'
  15.  * echo the array as JSON for a AJAX request to parse
  16.  * @return [type] [description]
  17.  */
  18. function get_all_questions() {
  19.  
  20.     $questions = [];
  21.  
  22.     $all_questions = get_posts( [
  23.         'post_type' => 'questions',
  24.         'numberposts' => -1,
  25.  
  26.     ]  );
  27.  
  28.     if ( sizeof( $all_questions ) > 0 ) {
  29.         foreach( $all_questions as $item ) {
  30.             // get the terms for the grades taxonomy on this question
  31.             $terms = get_the_terms( $item->ID , 'grades' );
  32.             // just return the name instead of the entire object
  33.             $terms = array_map( function($v) { return $v->name; } , $terms );
  34.  
  35.             $questions[] = [
  36.                                 'id' => $item->ID,
  37.                                 'title' => $item->post_title,
  38.                                 'grades' => $terms,
  39.                             ];
  40.         }
  41.     }
  42.  
  43.     echo json_encode( [ 'data' => $questions ] );
  44.  
  45.     // DONT FORGET THAT WE NEED TO USE wp_die(),
  46.     // otherwise the return will be messed up with the rest of a regular WP-page.
  47.     wp_die();
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement