NEXT craftinamerica.org. Base setup for headless wordpress https://www.craftinamerica.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

class.make-sortby.php 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. class Make_Sort_By extends WP_REST_Controller {
  3. private $post_type;
  4. private $sort_type;
  5. function __construct($sort_type, $post_type) {
  6. $this->post_type = $post_type;
  7. $this->sort_type = $sort_type;
  8. }
  9. /**
  10. * Register the routes for the objects of the controller.
  11. */
  12. public function register_custom_route($route) {
  13. $version = '2';
  14. $namespace = 'craft/v' . $version;
  15. register_rest_route( $namespace, '/' . $route . '/' . $this->post_type, [
  16. array(
  17. 'methods' => WP_REST_Server::READABLE,
  18. 'callback' => array( $this, $this->sort_type )
  19. ),
  20. ]);
  21. }
  22. public function by_alpha( $request ) {
  23. $params = $request->get_params();
  24. global $wpdb;
  25. $res = $wpdb->get_results($wpdb->prepare(
  26. "SELECT * FROM wp_posts
  27. WHERE post_type = %s
  28. AND post_status='publish'
  29. ORDER BY SUBSTRING_INDEX(post_title, ' ', -1)",
  30. $this->post_type
  31. ));
  32. wp_reset_postdata();
  33. $collection = array();
  34. forEach( $res as $key=>$item ) {
  35. $filtered = array();
  36. $filtered[id] = $item->ID;
  37. $filtered[slug] = $item->post_name;
  38. $filtered[type] = $item->post_type;
  39. $filtered[title] = $item->post_title;
  40. $filtered[excerpt] = $item->post_excerpt;
  41. $filtered[date] = $item->post_date;
  42. $filtered[content] = $item->post_content;
  43. $filtered[hero] = get_post_meta( $item->ID, 'hero_header', true );
  44. $collection[$key] = $filtered;
  45. };
  46. return new WP_REST_Response( $collection, 200 );
  47. }
  48. }
  49. ?>