I have a post type Properties. Property have their name(Title) image(Featured Image) and Locations(Acf Field). so i want to extract the exact property. from frontend i have a search form in which i am searching properties using location. so can i get the exact property using URL Like domain/wp-json/wp/v2/properties?acf.address_map.address="formsearchlocation
so it only return the property which has the same location as i searched Using wp rest api and frontend on react so if anybody can help me out reply !!
(I don’t want to fetch all location first and than filter out the specific location
try:- domain/wp-json/wp/v2/properties?acf.address_map.address="new-jersey"
Expectation :- title : Broadway Home
Image : domian/uploads/media/broadway.webp
Location : new-jersey United States
Output :- [
{
"id": 11371,
"title": "Business Address"
"acf" : {
"address_map" : {
"location" : "West 40th Street, New York, NY 10018",
}
}
},{
"id": 11352,
"title": "Prime Address"
"acf" : {
"address_map" : {
"location" : "West 40th Street, London",
}
}
},
{
"id": 11371,
"title": "Business Address 2"
"acf" : {
"address_map" : {
"location" : "East 40th Street, australia",
}
}
},{
"id": 11352,
"title": "Prime Address 2"
"acf" : {
"address_map" : {
"location" : "new-jersey United States",
}
}
},
]
1
For filtering properties by specific location using REST API we need to create custom REST API or endpoint which will filter data for you.
Below is the code to create REST API endpoint
in WordPress which you can add to functions.php
file of your theme.
function register_properties_route() {
register_rest_route('custom/v1', '/properties', array(
'methods' => 'GET',
'callback' => 'get_properties_by_location',
'args' => array(
'location' => array(
'required' => true,
'validate_callback' => function($param, $request, $key) {
return is_string($param);
}
),
),
));
}
add_action( 'rest_api_init', 'register_properties_route' );
function get_properties_by_location( $request ) {
$location = sanitize_text_field( $request['location'] );
$args = array(
'post_type' => 'properties',
'meta_query' => array(
array(
'key' => 'address_map_location', // Replace with your actual ACF field key
'value' => $location,
'compare' => 'LIKE'
)
)
);
$query = new WP_Query( $args );
$posts = array();
if ( $query->have_posts() ) {
while ($query->have_posts()) {
$query->the_post();
$posts[] = array(
'id' => get_the_ID(),
'title' => get_the_title(),
'acf' => get_fields(get_the_ID())
);
}
wp_reset_postdata();
}
return new WP_REST_Response( $posts, 200 );
}
You can use this endpoint to filter properties as per your need. Here is the sample function you can use in ReactJS
.
const [properties, setProperties] = useState([]);
const handleSearch = async () => {
try {
const response = await axios.get(`/wp-json/custom/v1/properties`, {
params: {
location: location,
},
});
setProperties( response.data );
} catch (error) {
console.error( 'Error in fetching properties:', error );
}
};