d2321
3/19/2020 - 11:07 PM

WP REST Custom Route v2

<?php

class all_terms
{
    public function __construct()
    {
        register_rest_route('wp/v2', '/all-terms', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_all_terms'),
        ));
    }

    public function get_all_terms($object)
    {
        $return = array();
		
		$out = get_posts(array('lang' => 'pl', 'post_type' => 'oferta', 'showposts' => -1));
		$arr_posts_titles = array();
		
		for($i=0;$i<count($out);$i++) {
			$ID = $out[$i]->ID;
			
			$arr_posts_titles[$i]['id'] = $ID;
			$arr_posts_titles[$i]['title'] = $out[$i]->post_title;
			$arr_posts_titles[$i]['ofs_left_list'] = get_field('ofs_left_list', $ID);
			$arr_posts_titles[$i]['agents'] = get_field('agents', $ID);
			
		}
		
		$return['d_params'] = $_GET;
        $return['d_test'] = $arr_posts_titles;
        //$return['debug'] = $out;
		
        return new WP_REST_Response($return, 200);
    }
}

add_action('rest_api_init', function () {
    $all_terms = new all_terms;
});
<?php 
$posts = json_decode( wp_remote_retrieve_body( wp_remote_get('http://site.loc/wp-json/wp/v2/all-terms') ), true );
print_r($posts);
?>