WordPress Rest API Custom Filters (Video Tutorials Notes) - Check out the video: https://www.youtube.com/watch?v=5rSfAkLO5eo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: Custom API | |
* Plugin URI: http://chrushingit.com | |
* Description: Crushing it! | |
* Version: 1.0 | |
* Author: Art Vandelay | |
* Author URI: http://watch-learn.com | |
*/ | |
function wl_products($params) { | |
$price = json_decode($params->get_param('price')); | |
function queryArgument($param, $key) { | |
if(is_object($param)) { | |
if($param->lt && $param->gt) { | |
return [ | |
[ | |
'key' => $key, | |
'value' => [$param->gt, $param->lt], | |
'type' => 'NUMERIC', | |
'compare' => 'BETWEEN' | |
] | |
]; | |
} | |
if($param->lt) { | |
return [ | |
[ | |
'key' => $key, | |
'value' => $param->lt, | |
'type' => 'NUMERIC', | |
'compare' => '<' | |
] | |
]; | |
} | |
if($param->gt) { | |
return [ | |
[ | |
'key' => $key, | |
'value' => $param->gt, | |
'type' => 'NUMERIC', | |
'compare' => '>' | |
] | |
]; | |
} | |
} | |
if($param) { | |
return [ | |
[ | |
'key' => $key, | |
'value' => $param, | |
'type' => 'NUMERIC' | |
] | |
]; | |
} | |
return null; | |
} | |
$args = [ | |
'posts_per_page' => 99999, | |
'post_type' => 'product', | |
'meta_query' => queryArgument($price, 'price') | |
]; | |
$posts = new WP_Query($args); | |
$data = []; | |
$i = 0; | |
foreach($posts->posts as $post) { | |
$data[$i]['id'] = $post->ID; | |
$data[$i]['title'] = $post->post_title; | |
$data[$i]['slug'] = $post->post_name; | |
$data[$i]['price'] = intval(get_field('price', $post->ID)); | |
$data[$i]['delivery'] = get_field('delivery', $post->ID); | |
$i++; | |
} | |
return $data; | |
} | |
add_action('rest_api_init', function() { | |
register_rest_route('wl/v1', 'products', [ | |
'methods' => 'GET', | |
'callback' => 'wl_products', | |
]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment