post_type = $post_type; } /** * Register the routes for the objects of the controller. */ public function register_routes($route) { $version = '2'; $namespace = 'craft/v' . $version; register_rest_route( $namespace, '/' . $route, [ array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'args' => array(), ), ]); register_rest_route( $namespace, '/' . $route . '/(?P[\d]+)', [ array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'args' => array( 'context' => array( 'default' => 'view', ), ), ), ]); } public function get_items( $request ) { $args = array( 'post_type' => $this->post_type, ); //do a query, call another class, etc $items = new WP_Query($args); $data = array(); foreach( $items as $item ) { // Get those Block! $item->blocks = parse_blocks( $item->post_content );; $itemdata = $this->prepare_item_for_response( $item, $request ); if($item->ID > 0) { $data[$item->ID] = $this->prepare_response_for_collection( $itemdata ); } } wp_reset_postdata(); return new WP_REST_Response( $data, 200 ); } public function get_item( $request ) { $params = $request->get_params(); $args = array( 'numberposts' => 1, 'orderby' => 'date', 'order' => 'DESC', 'post_type' => $this->post_type, ); //do a query, call another class, etc $item = new WP_Query($args); $data = $this->prepare_item_for_response( $item, $request ); wp_reset_postdata(); //return a response or error based on some conditional if ( 1 == 1 ) { return new WP_REST_Response( $data, 200 ); } else { return new WP_Error( 'code', __( 'message', 'text-domain' ) ); } } public function prepare_item_for_response( $item, $request ) { $filtered = array(); $filtered[id] = $item->ID; $filtered[type] = $item->post_type; $filtered[title] = $item->post_title; $filtered[excerpt] = $item->post_excerpt; $filtered[date] = $item->post_date; $filtered[content] = $item->post_content; $filtered[blocks] = get_rearrange_blocks($item->blocks); // return $item; if($item->post_status === 'publish') return $filtered; } } ?>