Last active
August 3, 2023 16:21
-
-
Save Saoming/8c326189dd7c9586c675ada4d29be79f to your computer and use it in GitHub Desktop.
(WP) Create your ownRest API endpoints
This file contains hidden or 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 | |
add_action('rest_api_init', function () { | |
register_rest_route('custom/v1', '/transactions/', [ | |
'methods' => 'GET', | |
'callback' => 'get_transactions', | |
]); | |
}); | |
function get_transactions($request) { | |
$paged = $request->get_param('page') ? $request->get_param('page') : 1; | |
$year = $request->get_param('year') ? $request->get_param('year') : NULL; | |
$args = [ | |
'post_type' => 'transaction', | |
'posts_per_page' => -1, | |
'paged' => $paged, | |
'tax_query' => [], | |
'orderby'=> 'date', | |
'order' => 'DESC' | |
]; | |
if($year) { | |
$args['meta_query'] = [ | |
[ | |
'key' => 'transaction_announcement_date', | |
'compare' => 'LIKE', | |
'value' => $year, | |
], | |
]; | |
} | |
$taxonomies = [ | |
'transaction-type' => 'transaction-type', | |
'location' => 'location', | |
'sector' => 'sector', | |
'subsector' => 'subsector', | |
]; | |
foreach ($taxonomies as $param => $taxonomy) { | |
if (!empty($request->get_param($param))) { | |
$args['tax_query'][] = [ | |
'taxonomy' => $taxonomy, | |
'field' => 'slug', | |
'terms' => explode(',', $request->get_param($param)), | |
]; | |
} | |
} | |
$query = new WP_Query($args); | |
if ($query->have_posts()) { | |
$transactions = []; | |
while ($query->have_posts()) { | |
$query->the_post(); | |
$transactions[] = [ | |
'ID' => get_the_ID(), | |
'title' => get_the_title(), | |
'link' => get_permalink(), | |
'year' => wp_date('Y', strtotime(get_field('transaction_announcement_date'))), | |
'content' => get_the_content(), | |
'acf' => get_fields(), | |
]; | |
} | |
wp_reset_postdata(); | |
return new WP_REST_Response($transactions, 200); | |
} else { | |
return new WP_Error('no_transactions', 'No transactions found', ['status' => 404]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment