Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * adds the ability to use the following url to get something
- *
- * https://www.domainname.com/wp-admin/admin-ajax.php?action=all_questions
- *
- * notice that we add it twice: the first is for logged in users, the second one for non-logged in users, so without privileges
- *
- */
- add_action( 'wp_ajax_all_questions' , 'get_all_questions' );
- add_action( 'wp_ajax_nopriv_all_questions' , 'get_all_questions' );
- /**
- * Get all posts from a CPT called 'questions'
- * echo the array as JSON for a AJAX request to parse
- * @return [type] [description]
- */
- function get_all_questions() {
- $questions = [];
- $all_questions = get_posts( [
- 'post_type' => 'questions',
- 'numberposts' => -1,
- ] );
- if ( sizeof( $all_questions ) > 0 ) {
- foreach( $all_questions as $item ) {
- // get the terms for the grades taxonomy on this question
- $terms = get_the_terms( $item->ID , 'grades' );
- // just return the name instead of the entire object
- $terms = array_map( function($v) { return $v->name; } , $terms );
- $questions[] = [
- 'id' => $item->ID,
- 'title' => $item->post_title,
- 'grades' => $terms,
- ];
- }
- }
- echo json_encode( [ 'data' => $questions ] );
- // DONT FORGET THAT WE NEED TO USE wp_die(),
- // otherwise the return will be messed up with the rest of a regular WP-page.
- wp_die();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement