Search code examples
ajaxwordpresswordpress-plugin-creationwordfence

How to avoid WordFence block for ajax calls in custom WordPress plugin


I am beginner developer and I am developing a custom wordpress plugin and the code itself worked as expected until we installed WordFence plugin for security issues.

After WF installation every other plugin on the website works smoothly as before, except the plugin I am developing - its AJAX calls get cought by Wordfence security and are being blocked (an alert message appears asking whether I'd like to add the call to white list, so it wont be blocked in the future). If I add it to the while list, the problem disappears for a while, but I don't like this solution and would like to make my code failproof.

I was trying to investigate some of the ajax calls in another plugins of ours, but I didn't manage to find any differencies which explain why the ajax from the other plugins is not blocked.

Here is an example code of my ajax calls:

jQuery.ajax({
        type: 'POST',
        url: my_ajax_object.ajax_url,
        async: true,
        dataType: 'json',
        data: {
            action: 'my_action',
            nonce: my_ajax_object.nonce,
        },
        success: function (resp) {
            }

and my php side:

add_action( 'admin_enqueue_scripts', 'my_enque_scripts' );
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_enque_scripts() {
  wp_enqueue_script( 'my_js', plugins_url( 'fly-academy-daily-planner/functions.js', __FILE__ ), array( 'jquery' ), '1', true );
  wp_localize_script(
    'my_js',
    'my_object',
    [
      'ajax_url' => admin_url('admin-ajax.php'),
      'nonce' => wp_create_nonce( 'my_js' ),
    ]
  );
}

function my_action () {};

I renamed my functions and variables for simplicity and please excuse any minor mismatch if any.

Every recommendation for how to modify this code to avoid unneccessary WordFence blocks programatically would be very appreciated !!


Solution

  • Problem solved! Turns out the root of the problem to be a html string parsed to the server with the ajax call. When I edit it to JSON it does not appear.