Skip to content

Instantly share code, notes, and snippets.

@CallumPrimeDev
Created November 18, 2024 14:48
Show Gist options
  • Save CallumPrimeDev/a52025f1d0a7d0bf6052027f7c2dded3 to your computer and use it in GitHub Desktop.
Save CallumPrimeDev/a52025f1d0a7d0bf6052027f7c2dded3 to your computer and use it in GitHub Desktop.
A custom endpoint that updates the price field and opening bid (custom field) for a given property
<?php
add_action('rest_api_init', function () {
register_rest_route('ppa/v1', '/update-property/', array(
'methods' => 'POST',
'callback' => 'update_property',
'permission_callback' => 'basic_auth_permission_check'
));
});
function update_property(WP_REST_Request $request) {
$params = $request->get_json_params();
$property_id = $params['id'];
$price = $params['price'];
$opening_bid = $params['_opening_bid'];
$department = $params['department'];
$hardcoded_post_id = 1059;
$test_post = get_post( $hardcoded_post_id );
$post_data = array(
'ID' => $hardcoded_post_id,
);
if ($department == 160534) {
update_post_meta($property_id, '_opening_bid', $opening_bid);
update_post_meta($property_id, '_price', $price);
$result = wp_update_post($post_data);
do_action( "save_post", $hardcoded_post_id, $test_post, false );
} else {
update_post_meta($property_id, '_commercial_opening_bid', $opening_bid);
update_post_meta($property_id, '_price_from', $price);
update_post_meta($property_id, '_price_to', $price);
do_action( "save_post", $hardcoded_post_id, $test_post, false );
}
// // // Create an array with just the post ID
// // $post_data = array(
// // 'ID' => $hardcoded_post_id,
// // );
// // // Update the post
// // $result = wp_update_post($post_data);
if (is_wp_error($result)) {
error_log("Error updating post: " . $result->get_error_message());
return new WP_REST_Response(array(
'status' => 'error',
'message' => $result->get_error_message()
), 500);
}
return new WP_REST_Response(array(
'status' => 'success',
'message' => 'Property updated successfully',
'result' => $result
), 200);
}
function basic_auth_permission_check() {
// Check if the user is authenticated
if (!isset($_SERVER['PHP_AUTH_USER'])) {
return new WP_Error('rest_forbidden', 'Authentication required', array('status' => 401));
}
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
// Authenticate the user
$user = wp_authenticate($username, $password);
if (is_wp_error($user)) {
return new WP_Error('rest_forbidden', 'Invalid credentials', array('status' => 403));
}
// Set the current user
wp_set_current_user($user->ID);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment