wordpress--adding JavaScript and Ajax to the Plugin admin page

Source: Internet
Author: User
Tags script tag



Recently in the development of a WordPress plugin, you need to add your own JavaScript files on the plugin's admin page to achieve some functionality.



After several days of documentation and information, and finally realized.



Here first introduce the next WordPress background page to add JavaScript process, and then introduce the process of adding Ajax.





Add JavaScript


First we need to know the framework of WordPress plugin development, and then introduce the steps that JavaScript adds.


Add Plugin Settings page


The development of plug-ins, the total need to add their own plug-in settings in the background page, plug-in Settings sub-page, in these pages, you can set and save some of the plug-in operating parameters.



You can add a plug-in Settings page to multiple locations in the admin background. The default admin backend pane of WordPress provides default master page menus such as page, post, comment, and setting.



As shown in, this is the main Page menu for "articles," "pages," "Comments," and "settings" in Chinese. WordPress provides the corresponding API, at the bottom of these locations, to add pages.



For example, we can add our own plugin Settings page under "Settings", using the API:

add_options_page ($ page_title, $ menu_title, $ capability, $ menu_slug, $ function);
We can also add our own plugin settings page under "Comments", using the API:

add_comments_page ($ page_title, $ menu_title, $ capability, $ menu_slug, $ function);
However, we can also add our plugin settings page at the same level as "page", "article", "comment". For example, in, the setting page of my plugin "cartbiner server" is at the same level as "article". Then under this plug-in settings page, we add related subpages on our own.

The API we want to use is, specific parameters and meanings can be found in wordpress codex:

add_menu_page ();
add_submenu_page ();

The final result of my implementation is that the main settings page of 1 plugin and the sub-setting pages of 3 plugins:

 

For details, please refer to:

Wordpress background management page development

 

Add javascript file
What we want to talk about here is how to add a javascript file on the plugin settings page.

As a developer, we can use the script tag directly in the output html page and add javascript code.

However, Wordpress does not recommend this. First, it is not easy to manage, but it is difficult to avoid errors caused by the repetition of multiple codes.

So what we are going to say here is actually to use the interface provided by wordpress to add javascript files in the corresponding page headers.

For example, we added 3 sub-setting pages above, but we want to develop a javascript file that will only be added to the "Add Cartbinet" and "Add Door" pages. No other pages will contain this javascript file.

wordpress provides 2 ways to add javascript, but I only tried one, and then I will introduce my implementation method in detail.

What types of pages can add javascript files?
In wordpress, there are the following several page positions, you can add user-defined javascript files.

They are:

Background management page;
Administrator's login page;
Front page (that is, the page that general visitors see).
The following is an excerpt from the official development tutorial of the wordpress plugin:

For administration pages, use admin_enqueue_scripts.

For front-end pages use wp_enqueue_scripts, except for the login page, in which case use login_enqueue_scripts.

You can see that there are 3 APIs in total, and you can add javascript files to the above three page types.

Obviously, what we will use here is the API:

admin_enqueue_scripts ();
The process of adding javascript files
 First of all, in the init_hooks function of the plugin, when WordPress loads the background management menu and page, add our own plugin settings page:

add_action (‘admin_menu‘, array (‘CartbinetServer‘, ‘cartbinet_add_pages’));
add_action (‘admin_enqueue_scripts’, array (‘CartbinetServer’, ‘cartbinet_load_add_cartbinet_scripts’));
The first add_action is used to add our own plugin settings page.

"Admin_menu", which means wordpress is loaded into the background management menu and page hook;

"Cartbinet_add_pages", add the function of plugin setting page;

The second add_action is used to load our javascript file.

"Admin_enqueue_scripts", which means the hook of the javascript file that wordpress inserts into the management page;

"Cartbinet_load_add_cartbinet_scripts", a function to load javascript files.

We introduce these two functions in steps: "cartbinet_add_pages" and "cartbinet_load_add_cartbinet_scripts".

 

Secondly, in the function of adding a plugin setting page, which is cartbinet_add_pages, get the hook of the page where we need to add a javascript file. That is to say, on which page we want to add a javascript file, we need to get a logo of this page-hook.

This hook is the return value of the following API. We store the page in a global array variable so that other functions can also access it:

$ addCartBinetsPageHook = add_submenu_page;
$ addDoorPageHook = add_submenu_page
The above code is just a representation, not complete. Readers can consult the API: add_submenu_page.

 

Next, we write the following code in the function of loading javascript files in the background management page, that is, the function "cartbinet_load_add_cartbinet_scripts".

At the beginning of this function, we first determine whether the current management page is the two plug-in sub-setting pages where we need to add a javascript file.

public static function cartbinet_load_add_cartbinet_scripts ($ hook) {
If (! In_array ($ hook, self :: $ addPages))
Return;

/ * Put jquery scriptr in the queue * /
Wp_enqueue_script (‘setting-ajax-script‘, plugins_url (‘accerts / js / setting.js’, __FILE__));

$ Title_nonce = wp_create_nonce (‘title_example’);
Wp_localize_script (‘setting-ajax-script’,
‘My_ajax_obj’,
Array (
‘Ajax_url’ => admin_url (‘admin-ajax.php’),
‘Nonce’ => $ title_nonce,
));
}

wp_enqueue_script is the function to register javascript files.

As for wp_localize_script, it is a function to register ajax.

wp_create_nonce is a function that generates an ajax interactive key, which means that the server generates a key. When the front-end javascript requests service data from the server through ajax, it needs to send this key for verification.

 

Add ajax
The steps for adding ajax are actually the same as the steps for adding javascript files.

First, in the init_hooks function, register the server ajax response function:

add_action (‘wp_ajax_cartbinet_name_list’, array (‘CartbinetServer‘, ‘cartbinet_name_list_ajax_handler’));
Our ajax response function is:

public static function cartbinet_name_list_ajax_handler () {
    // check nonce
    check_ajax_referer (‘title_example’);

    error_log (‘cartbinet_name_list_ajax_handler’);

    // get cartbinet name list from xml file, json format
    $ names = self :: cartbinet_get_name_list ();

    error_log (implode ("", $ names));

    // return data to front end jquery script
    wp_send_json ($ names);

    wp_die (); // all ajax handlers should die when finished
}
 

Second, in the function that loads the javascript file, register the global variables to be used in the ajax interaction, and the url location sent by the ajax request.

Why do you do this,

Because the ajax request is placed in the javascript file, first load the javascript file, and secondly, generate the ajax key on the server side. Finally, register an ajax request and the variables and url location that the interactive request will use on the server side.

public static function cartbinet_load_add_cartbinet_scripts ($ hook) {
If (! In_array ($ hook, self :: $ addPages))
Return;

/ * Put jquery scriptr in the queue * /
Wp_enqueue_script (‘setting-ajax-script‘, plugins_url (‘accerts / js / setting.js’, __FILE__));

$ Title_nonce = wp_create_nonce (‘title_example’);
Wp_localize_script (‘setting-ajax-script’,
‘My_ajax_obj’,
Array (
‘Ajax_url’ => admin_url (‘admin-ajax.php’),
‘Nonce’ => $ title_nonce,
));
}

 

 

 

Finally, we implement the javascript file in the front-end page,

jQuery (document) .ready (function ($) {// wrapper
    
    var this2 = $ ("# filter-by-name");
    $ .post (my_ajax_obj.ajax_url, {// POST request
        _ajax_nonce: my_ajax_obj.nonce, // nonce
         action: "cartbinet_name_list", // action
         title: ‘cartbinets_names’ // data
     }, function (data) {// callback
         $ (this2) .empty ();
         $ .each (data, function (key, value) {
             var $ op = new String ("<option>" + value + "</ option>");
             $ (this2) .append ($ op);
         });
     });
});
"My_ajax_obj" is the ajax variable generated by the server-side PHP:

"My_ajax_obj.ajax_url", save the url address to send ajax request to the server;

"My_ajax_obj.nonce", Save the ajax interaction key.

"Cartbinet_name_list" corresponds to the ajax request ID registered on the PHP side of the server, that is, the ajax request ID set when the ajax response function is registered in the init_hook function.

That is to say, this ajax request sent by the front end will be parsed by wordpress, and then the server-side php will know to call the function "cartbinet_name_list_ajax_handler" according to the ajax request ID, in response to this ajax request.

 

 

add_action (‘wp_ajax_cartbinet_name_list’, array (‘CartbinetServer‘, ‘cartbinet_name_list_ajax_handler’));
 

"Data", which stores the data returned by the server through the function wp_send_json ($ names).

 

Reference materials:
https://developer.wordpress.org/plugins/javascript/enqueuing/

http://www.solagirl.net/wordpress-ways-to-load-js-css.html

https://www.zfanw.com/blog/wordpress-add-jquery.html

 

wordpress-add javascript and ajax to the plugin background management page

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.