Created
January 5, 2025 15:22
-
-
Save g-maclean/e0a66f13a1de20211c69511e3b884009 to your computer and use it in GitHub Desktop.
propertyhive - rest endpoint for getting slug from ref number
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
| /** | |
| * rest api ref lookup | |
| */ | |
| // Register the REST API route | |
| add_action('rest_api_init', function () { | |
| register_rest_route('property/v1', '/lookup', [ | |
| 'methods' => 'GET', | |
| 'callback' => 'get_property_slug_by_ref', | |
| 'args' => [ | |
| 'ref' => [ | |
| 'required' => true, | |
| 'validate_callback' => function ($param) { | |
| return is_string($param) && !empty($param); | |
| } | |
| ] | |
| ], | |
| 'permission_callback' => '__return_true', // Allow public access | |
| ]); | |
| }); | |
| /** | |
| * Callback function to fetch the slug by reference number | |
| */ | |
| function get_property_slug_by_ref($request) { | |
| // Get and sanitize the 'ref' parameter | |
| $ref = sanitize_text_field($request->get_param('ref')); | |
| // Query for the property using the sanitized reference number | |
| $query = new WP_Query([ | |
| 'post_type' => 'property', // Change 'property' to your custom post type | |
| 'meta_key' => '_reference_number', // Replace with your meta key | |
| 'meta_value' => $ref, | |
| 'posts_per_page' => 1, | |
| ]); | |
| if ($query->have_posts()) { | |
| $query->the_post(); | |
| $slug = get_post_field('post_name', get_the_ID()); | |
| wp_reset_postdata(); | |
| return [ | |
| 'status' => 'success', | |
| 'slug' => $slug, | |
| ]; | |
| } else { | |
| return new WP_Error('no_property', 'No property found with this reference number', ['status' => 404]); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment