Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- add_action( 'rest_api_init', function () {
- // Path to meta query route e.g. localhost:3000/wp-json/reazul/v1/daily_post?for_day=10&for_month=3
- register_rest_route( 'reazul/v1', '/daily_post', array(
- 'methods' => 'GET', // API request method
- 'callback' => 'get_daily_post', // Call back to process request
- 'args' => array( // Arguments passed on to the callback and their validations
- 'for_day' => array(
- 'required' => true,
- 'validate_callback' => function($param, $request, $key) {
- return is_numeric( $param ); // Checking for if the value is a number e.g. 1-31
- }
- ),
- 'for_month' => array(
- 'required' => true,
- 'validate_callback' => function($param, $request, $key) {
- return is_numeric( $param ); // Checking for if the value is a number e.g. 1-12
- }
- ),
- )
- ) );
- });
- // Callback function that returns API contents
- function get_daily_devotional( WP_REST_Request $request ) {
- $args = array(
- 'numberposts' => 1,
- 'post_type' => 'post',
- 'meta_query' => array(
- 'relation' => 'AND', // Relationship between two variables passed onto callback
- array(
- 'key' => 'date', // ACF field key
- 'value' => "".$request->get_param( 'for_day' )."", // Getting query value from request. Additional Quote is used for turning it to string.
- 'compare' => 'LIKE',
- ),
- array(
- 'key' => 'month', // ACF field key
- 'value' => "".$request->get_param( 'for_month' )."", // Getting query value from request. Additional Quote is used for converting it to string.
- 'compare' => 'LIKE',
- ),
- )
- );
- $the_query = new WP_Query( $args );
- // Regular post loop
- if( $the_query->have_posts() ) {
- $data = array();
- while($the_query->have_posts()) {
- $the_query->the_post();
- // Generating custom API contents
- $data['ID'] = get_the_ID();
- $data['title'] = get_the_title();
- $data['permalink'] = get_the_permalink();
- $data['excerpt'] = wp_trim_words(get_the_content(), 75);
- $data['content'] = get_the_content();
- }
- return $data;
- } else {
- return new WP_Error( 'no_post', 'No post to show.', array( 'status' => 404 ) );
- }
- }
Add Comment
Please, Sign In to add comment