NEXT craftinamerica.org. Base setup for headless wordpress https://www.craftinamerica.org
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

class.make-endpoint.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. include('reformat-blocks.php');
  3. include('related-items.php');
  4. include('formats.php');
  5. class Make_Endpoint_For extends WP_REST_Controller {
  6. private $post_type;
  7. function __construct($post_type) {
  8. $this->post_type = $post_type;
  9. }
  10. /**
  11. * Register the routes for the objects of the controller.
  12. */
  13. public function register_custom_route($route) {
  14. $version = '2';
  15. $namespace = 'craft/v' . $version;
  16. register_rest_route( $namespace, '/' . $route, [
  17. array(
  18. 'methods' => WP_REST_Server::READABLE,
  19. 'callback' => array( $this, 'get_items' )
  20. ),
  21. ]);
  22. register_rest_route( $namespace, '/' . $route . '/(?P<id>[\d]+)', [
  23. array(
  24. 'methods' => WP_REST_Server::READABLE,
  25. 'callback' => array( $this, 'get_items' )
  26. ),
  27. ]);
  28. }
  29. public function get_items( $request ) {
  30. $args = array(
  31. 'numberposts' => -1,
  32. 'post_type' => $this->post_type,
  33. // Order DOES NOT WORK because you're
  34. // returning the posts by id - DUH
  35. // 'orderby' => 'date',
  36. // 'order' => 'DESC'
  37. );
  38. // Get parameters from request
  39. // /<id>?limit=<num>
  40. $params = $request->get_params();
  41. if(intval($params['limit']) > 0) { $args['numberposts'] = intval($params['limit']); }
  42. if(intval($params['id']) > 0) { $args['include'] = array($params['id']); }
  43. // !: Add order asc/desc
  44. // !: Add orderby
  45. return new WP_REST_Response( $this->prepare_item_for_response($args), 200 );
  46. }
  47. public function prepare_item_for_response( $args ) {
  48. $collection = array();
  49. // https://developer.wordpress.org/reference/functions/get_posts/
  50. foreach( get_posts($args) as $item ) {
  51. $filtered = default_post_format($item);
  52. // Get those Block!
  53. $filtered[blocks] = get_rearrange_blocks(
  54. parse_blocks( $item->post_content )
  55. );
  56. $filtered[hero] = get_post_meta( $item->ID, 'hero_header', true );
  57. $filtered[relatedto] = p2p_related_to($item->ID, $item->post_type);
  58. $collection[$item->ID] = $filtered;
  59. }
  60. wp_reset_postdata();
  61. return $collection;
  62. }
  63. }
  64. ?>