Use Ajax with WordPress administration screen

Other language site
ja ja
Google Translate
  • -

    シェア
  • ---

    LINEで送る
  • -

    はてなブックマーク
    ブックマーク
  • -

    pocket
  • -

    rss
WordPress logo

This is how to implement Ajax when creating WordPress management screen.

JavaScript

Register queue of js file

First, register the js file describing ajax processing in the queue so that it is displayed as "<script type = 'text / javascript' src = '**. Js'> </ script>" in html. Write it in a .php file with the same name as the plugin's home directory, which is the functions.php of the plugin.

function load_tdy_sns_mng_admin_script() {
    add_action('admin_enqueue_scripts', function() {
        wp_register_script('js_handle_name', plugins_url('**/js/clear-cache.js', __FILE__), array('jquery'), '1.0.0', true);
        wp_localize_script('js_handle_name', 'localize', array('ajax_url' => admin_url('admin-ajax.php')));
        wp_enqueue_script('js_handle_name');
    } );
}

The important point is wp_localize_script().

In order to use Ajax in WordPress management screen, you must send a request to url "//(host)/wp-admin/admin-ajax.php". To do that, you need to specify that path in ajax url of the js file to be described later.

wp_localize_spcipt() is a function that passes an object variable (localize) to the specified js file. In this case, the url of the management screen is put in the variable "ajax_url" and passed to the js file.
By doing this you do not need to write the url path directly in the js file.

admin_url() is a function that generates url of the management screen. Also, plugins_url('** / js / test.js', __FILE__) is a function to create the url of the plug-in being created. Specify its own file name with the second argument.

Contents of js file

For this time, use Ajax to asynchronously perform the process of clearing the cache file by clicking the button. The content of the js file is as follows.

function clearCacheSnsCount() {
    jQuery.ajax({
        type: "POST",
        url: localize.ajax_url,
        dataType: 'text',
        data: {
            action: 'clear_cache'
        }
    }).done(function(data, textStatus, jqXHR) {
        outputMsg(data);
    }).fail(function() {
        outputMsg('cache clear error!!');
    });
}

First of all, be careful not to use "$" when using jquery. This may be using various js libraries in the WordPress administration screen. So, "$" may conflict and not be recognized as jQuery.

Let's write it jQuery neatly here.

For ajax url, we specified the object variable specified in queue registration of js. It will be sent to "//(host)/wp-admin/admin-ajax.php" in this description.

"clear_cache" specified for the action of data has a meaning. Let's remember that this string specifies a function to process when receiving the request.

outputMsg() is a function created to output the processing result message. I will omit it here.

Additional notes (November 14, 2017)

(function ($) {}) (jQuery); You can use $ by enclosing the whole function.

(function($) {
    function clearCacheSnsCount() {
        $.ajax({
            type: "POST",
            url: localize.ajax_url,
            dataType: 'text',
            data: {
                action: 'clear_cache'
            }
        }).done(function(data, textStatus, jqXHR) {
            outputMsg(data);
        }).fail(function() {
            outputMsg('cache clear error!!');
        });
    }
})(jQuery);

Server processing (php)

The following function is the content of processing when receiving a request sent with ajax.

function clear_cache() {
    $cache_file = '../cache/11111111111111111.cache';
    $success = __('Complete clear cache');
    $error = __('Clear cache failer');
    $result = '';

    if(file_exists($cache_file)) {
        if(unlink($cache_file)) {
            $result = $success;
        } else {
            $result = $error;
        }
    } else {
        $result = $success;
    }
    echo $result;
    die();
}
add_action('wp_ajax_clear_cache', 'clear_cache');

The contents of processing are not particularly difficult. If there is a cache file, only the processing to delete, the processing result is returned by echo.

At the end of processing there is dir (). This is because "return 0;" is returned if "return" is omitted, 0 is attached to the processing result of ajax. In order to avoid this, we terminate the script with dir ().

Do not you think it strange here? Why is it possible for this function to receive what ajax requested?
The secret is in add_action ().

I sent "action" data with ajax request. Its value was "clear_cache". Actually, this value represents the "***" part of "wp_ajax _ ***" in the handle name of the action hook. By matching this string, a request sent by ajax is being received.

The string "action" must be original. You need to create a string that does not conflict with other plugins.

In this way you can do a series of processing to return the processing result from the request using ajax.

Conclusion

Originally, in order to implement secure ajax processing, we need to devise another one, but we do not implement it here.

It is realized by using wp_create_nonce() with wp_localize_script() used for queuing js, but I will make it another opportunity.

SNS also distributes articles.

コメント

  1. tadaya says:

    I added a method that jQuery $ can use.

Leave a Reply

*

If you like this article, share it!