| 1 |
<?php |
| 2 |
|
| 3 |
if ( ! defined( 'ABSPATH' ) ) { |
| 4 |
exit; // Exit if accessed directly. |
| 5 |
} |
| 6 |
|
| 7 |
add_action('rest_api_init', function () { |
| 8 |
register_rest_route('wdk/v1', '/listing/autosuggestion', [ |
| 9 |
'methods' => 'POST', |
| 10 |
'callback' => 'wdk_listing_search_rest_callback', |
| 11 |
'permission_callback' => function () { |
| 12 |
return current_user_can('edit_posts'); |
| 13 |
}, |
| 14 |
]); |
| 15 |
}); |
| 16 |
|
| 17 |
function wdk_listing_search_rest_callback($request) |
| 18 |
{ |
| 19 |
$params = $request->get_json_params(); |
| 20 |
$keyword = ''; |
| 21 |
|
| 22 |
if ($params && isset($params['keyword'])) { |
| 23 |
$keyword = sanitize_text_field($params['keyword']); |
| 24 |
} |
| 25 |
|
| 26 |
if (strlen($keyword) < 2) { |
| 27 |
return rest_ensure_response([ |
| 28 |
'success' => true, |
| 29 |
'data' => [] |
| 30 |
]); |
| 31 |
} |
| 32 |
|
| 33 |
$args = [ |
| 34 |
'post_type' => 'wdk-listing', |
| 35 |
'posts_per_page' => 10, |
| 36 |
's' => $keyword, |
| 37 |
]; |
| 38 |
|
| 39 |
// Optionally exclude the currently executed ID if provided |
| 40 |
if (isset($params['executedId'])) { |
| 41 |
$args['post__not_in'] = [intval($params['executedId'])]; |
| 42 |
} |
| 43 |
|
| 44 |
$posts = get_posts($args); |
| 45 |
|
| 46 |
$result = []; |
| 47 |
foreach ($posts as $post) { |
| 48 |
$result[] = [ |
| 49 |
'id' => $post->ID, |
| 50 |
'title' => $post->post_title, |
| 51 |
'edit' => urlencode(admin_url('admin.php?page=wdk_listing&id=' . $post->ID)), |
| 52 |
]; |
| 53 |
} |
| 54 |
|
| 55 |
return rest_ensure_response([ |
| 56 |
'success' => true, |
| 57 |
'data' => $result |
| 58 |
]); |
| 59 |
} |
| 60 |
|