Most common error by wordpress plug-in developer

There are several small small but serious mistacks done by most of the wordpress developer. Today I’ll discuss on adding js and css files in proper way and only in required page, this is the most common error by wordpress plug-in developer.

You can see mainly developers are adding the required js and css files with the help of script and link tag respectively. But it should not be done. As these tags might have been loaded already, so there’s no point in adding it again. Infact, they can break your complete site without let you know exactly where you are doing wrong.

So, by just adding this tags in your plug-in you’re ready for some trouble. 🙁

Now the question is how we will add js and css files in our custom plug-in?
Wordpress providing us wp_enqueue_script and wp_enqueue_style these two fuunctions for adding js and css files respectively.


Now the problem is custom js or CSS files added on each and every admin/frontend pages

Mean, suppose you have created one plug-in which will create 2 sub-menu under Settings tab in admin section. And for your custom functionality you need custom js and css files so using the wp_enqueue_script and wp_enqueue_style you have added those. Now the problem is if you install your plug-in and check then you will find that these js and css files are uploading through out the admin section means in all the admin pages. But the point is you need these custom js and css files only in 2 pages.

So my point is upload js and css files only on the page where they required. But the question is HOW? Dont worry it is very easy.

WordPress providing us a function to do that ‘admin_print_scripts-(page_hook)

$page_hook = add_management_page( 'myplugin', 'myplugin', 9, __FILE__, 'myplugin_admin_page' );
add_action( "admin_print_scripts-$page_hook", 'myplugin_admin_head' );
function myplugin_admin_head() {
// what your plugin needs in its <head>

You can download the below plug-in where I have created a two pages with different differe js and css files and these files are not loading any other pages.

DOWNLOAD: load-js-css