If you’re trying to implement a dependent picklist in a WordPress plugin and facing issues with AJAX and the WordPress database, you’re not alone. In this step-by-step guide, we’ll walk you through the process and help you overcome the challenges discussed in the community.

Understanding the Problem

The original code attempts to update a dropdown (#am_contact) based on the selection in another dropdown (#am_organisation). However, the approach taken, using a standalone PHP file (get-contacts.php), has limitations and can lead to issues with WordPress APIs.

The Issues Highlighted in the Discussion

  1. Missing WordPress API: The usage of a standalone PHP file means that WordPress API is not loaded, causing the $wpdb (WordPress Database) calls to fail.
  2. Security Concerns: A standalone PHP file poses security risks, and it’s recommended to use WordPress APIs for AJAX requests.

Solution: Use REST API Endpoint

To overcome these challenges, let’s implement a more robust solution using a REST API endpoint.

1. Register a REST API Endpoint

In your plugin or theme’s functions.php file, register a REST API endpoint. This ensures that WordPress APIs are loaded correctly.


add_action('rest_api_init', function () {
register_rest_route('harriecrm/v1', '/contacts/', array(
'methods' => 'GET',
'callback' => 'get_contacts'
));
});

function get_contacts($request) {
$id = $request['organisation_id'];
// Your database query and processing code goes here
return "result"; // Return the result as needed
}

2. Update AJAX Call

Modify your JavaScript to make an AJAX request to the newly created REST API endpoint.


$('#am_organisation').change(function(){
var val = $(this).val();
$.ajax({
type: 'GET', // Change from POST to GET
url: '/wp-json/harriecrm/v1/contacts',
data: 'organisation_id=' + val,
success: function(data){
$("#am_contact").html(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});

Advantages of Using REST API Endpoint

  1. Access to WordPress API: This approach ensures that the WordPress API, including $wpdb, is loaded, allowing for smooth database interactions.
  2. Improved Security: The REST API endpoint is a safer way to handle AJAX requests, reducing security risks associated with standalone PHP files.
  3. Flexibility and Documentation: The REST API allows for easy expansion, documentation, and self-validation of incoming data.
  4. Plugin Deactivation: The endpoint is active only when the plugin is active, enhancing security and closing potential security holes.
  5. Code Organization: You can now place your code anywhere in the plugin’s codebase.

By following these steps, you can create a more reliable and secure solution for implementing a dependent picklist in your WordPress plugin.

Leave a Reply

Your email address will not be published. Required fields are marked *