Created
June 6, 2024 09:05
-
-
Save hazratbilal0079/5a205801ee5ce5740febca1b71946a94 to your computer and use it in GitHub Desktop.
Assign Multiple Tickets/Properties or Update Single or Multiple Metafields from Frontend in WordPress through hook or Code Snippet
This file contains 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
--Hook Name | |
assignproperty | |
--Php Hook | |
add_action('jet-form-builder/custom-action/assignproperty', function($request, $action_handler) { | |
// Sanitize the input fields to prevent any security issues | |
$property_name = isset($_POST['select_property']) ? sanitize_text_field($_POST['select_property']) : ''; | |
$community_name = isset($_POST['community-name']) ? sanitize_text_field($_POST['community-name']) : ''; | |
$responsible_person = sanitize_text_field($_POST['responsible_person']); | |
// Validate that responsible_person is a number (user ID) | |
if (!is_numeric($responsible_person)) { | |
// If not a number, handle the error appropriately (log, return, etc.) | |
error_log('Invalid responsible_person value: must be a numeric user ID.'); | |
return; | |
} | |
// Convert responsible_person to an integer | |
$responsible_person = (int)$responsible_person; | |
// Use global $wpdb to access the WordPress database | |
global $wpdb; | |
// Initialize an empty array to store post IDs | |
$post_ids = array(); | |
// Check if property name has value | |
if (!empty($property_name)) { | |
// Prepare the SQL query to get the post ID of the 'owner-data' post type | |
// that has the given property_name meta field | |
$property_query = $wpdb->prepare( | |
"SELECT post_id | |
FROM {$wpdb->prefix}postmeta | |
WHERE meta_key = 'property-name' AND meta_value = %s", | |
$property_name | |
); | |
// Get the post IDs that match the query for property name | |
$post_ids = array_merge($post_ids, $wpdb->get_col($property_query)); | |
} | |
// Check if community name has value | |
if (!empty($community_name)) { | |
// Prepare the SQL query to get the post ID of the 'owner-data' post type | |
// that has the given community_name meta field | |
$community_query = $wpdb->prepare( | |
"SELECT post_id | |
FROM {$wpdb->prefix}postmeta | |
WHERE meta_key = 'community-name' AND meta_value = %s", | |
$community_name | |
); | |
// Get the post IDs that match the query for community name | |
$post_ids = array_merge($post_ids, $wpdb->get_col($community_query)); | |
} | |
// Remove duplicates from post IDs array | |
$post_ids = array_unique($post_ids); | |
// Loop through the post IDs and update the responsible_person meta field | |
foreach ($post_ids as $post_id) { | |
update_post_meta($post_id, 'responsible-person', $responsible_person); | |
} | |
}, 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment