run silex or slim with wordpress

There’s little that you can do with the Silex server that can’t be done through WordPress but it takes a bit of effort to get WP to respond to AJAX calls.

The first step is to make the call available through AJAX. This requires adding a line to your functions.php file similar to

add_action('wp_ajax_my_ajax_call', 'onno_update_my_ajax_call');

if this call will be made for guests and customers (i.e. not ADMIN), you’ll also need the line.

add_action('wp_ajax_nopriv_my_ajax_call', 'my_ajax_call');

which does the same thing but is more inclusive.

The next step is to create the ajax calls. You don’t give an example of such a call so all I can do is advise you to look at the docs for $wpdb. WP has a comprehensive set of calls for retrieving info from the database and for complex queries, you can always use $wpdb->query() which will run arbitrary SQL for you.

The AJAX logic goes in the function my_ajax_call() and the result should be placed into an array or object. The final line of your function should be a call to wp_send_json_success($return) where $return is the object/array of information to be returned.

Using this system, I’ve been able to add pages to the wp_admin section to allow shop owners to build purchase orders for restocking from WooCommerce data and a side-load gallery for variations (Woo only allows a gallery for the parent).

Here’s a quick example:

function my_ajax_call() {
    $return['data'] = date('Y-m-d');
    wp_send_json_success($return);
    wp_die();
}

And then in the javascript, more steps are necessary. For one thing, you’ll need the WP AJAX URL which is usually /wp-admin/admin-ajax.php but can vary somewhat. It’s often made available to Javascript as the global ajaxurl or might be tucked away in another object like woocommerce.ajaxurl. You’ll need to construct a Javascript object with an action element that points to your function and any other variables you might need to pass to the AJAX call. For example:

data = {'action':'my_ajax_call'}

or

data = {'action':'my_ajax_call', 'todo':'getDate'}

(function($){
    $.ajax{
        url:ajaxurl,
        data: data,
        success: function(trn) {$('#data').html(trn.data)}
})(jQuery)

HTH

Leave a Comment