Guest User

Untitled

a guest
Feb 23rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. add_action( 'rest_api_init', function () {
  2.  
  3. // Path to meta query route e.g. localhost:3000/wp-json/reazul/v1/daily_post?for_day=10&for_month=3
  4.  
  5. register_rest_route( 'reazul/v1', '/daily_post', array(
  6. 'methods' => 'GET', // API request method
  7. 'callback' => 'get_daily_post', // Call back to process request
  8. 'args' => array( // Arguments passed on to the callback and their validations
  9. 'for_day' => array(
  10. 'required' => true,
  11. 'validate_callback' => function($param, $request, $key) {
  12. return is_numeric( $param ); // Checking for if the value is a number e.g. 1-31
  13. }
  14. ),
  15. 'for_month' => array(
  16. 'required' => true,
  17. 'validate_callback' => function($param, $request, $key) {
  18. return is_numeric( $param ); // Checking for if the value is a number e.g. 1-12
  19. }
  20. ),
  21. )
  22. ) );
  23. });
  24.  
  25. // Callback function that returns API contents
  26.  
  27. function get_daily_devotional( WP_REST_Request $request ) {
  28.  
  29. $args = array(
  30. 'numberposts' => 1,
  31. 'post_type' => 'post',
  32. 'meta_query' => array(
  33. 'relation' => 'AND', // Relationship between two variables passed onto callback
  34. array(
  35. 'key' => 'date', // ACF field key
  36. 'value' => "".$request->get_param( 'for_day' )."", // Getting query value from request. Additional Quote is used for turning it to string.
  37. 'compare' => 'LIKE',
  38. ),
  39. array(
  40. 'key' => 'month', // ACF field key
  41. 'value' => "".$request->get_param( 'for_month' )."", // Getting query value from request. Additional Quote is used for converting it to string.
  42. 'compare' => 'LIKE',
  43. ),
  44. )
  45. );
  46. $the_query = new WP_Query( $args );
  47.  
  48. // Regular post loop
  49. if( $the_query->have_posts() ) {
  50. $data = array();
  51.  
  52. while($the_query->have_posts()) {
  53. $the_query->the_post();
  54.  
  55. // Generating custom API contents
  56. $data['ID'] = get_the_ID();
  57. $data['title'] = get_the_title();
  58. $data['permalink'] = get_the_permalink();
  59. $data['excerpt'] = wp_trim_words(get_the_content(), 75);
  60. $data['content'] = get_the_content();
  61. }
  62.  
  63. return $data;
  64. } else {
  65. return new WP_Error( 'no_post', 'No post to show.', array( 'status' => 404 ) );
  66. }
  67. }
Add Comment
Please, Sign In to add comment