Comment mettre en file d'attente des styles / scripts sur certaines pages / wp-admin?
-
-
Voir lesexemples de documentation officielle https://developer.wordpress.org/plugins/javascript/enqueuing/#enqueue http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts#Example:_Target_a_Specific_Admin_PageSee official documentation examples https://developer.wordpress.org/plugins/javascript/enqueuing/#enqueue http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts#Example:_Target_a_Specific_Admin_Page
- 0
- 2015-01-11
- paul
-
9 réponses
- votes
-
- 2012-02-04
add_menu_page
etadd_submenu_page
renvoienttous deux le "suffixe de hook" de lapage,quipeut être utilisépouridentifier lapage avec certains hooks. Entant quetel,vouspouvez utiliser ce suffixeen combinaison avec les crochets variablesadmin_print_styles-{$hook_suffix}
etadmin_print_scripts-{$hook_suffix}
pour cibler spécifiquement cespages.function my_menu() { $menu = add_menu_page( 'Page 1', 'bar', 'something', 'else', 'foo' ); $submenu = add_submenu_page( 'theme_menu', 'Subpage 1', 'Subpage', 'something', 'else', 'foo' ); add_action( 'admin_print_styles-' . $menu, 'admin_custom_css' ); add_action( 'admin_print_styles-' . $submenu, 'admin_custom_css' ); add_action( 'admin_print_scripts-' . $menu, 'admin_custom_js' ); add_action( 'admin_print_scripts-' . $submenu, 'admin_custom_js' ); }
Jetrouve que c'est uneméthodeproprepour ajoutertout cela cartoutestgéré dans une seulefonction. Si vous décidez de supprimer cettefonctionnalité,supprimez simplement l'appel à unefonction.
add_menu_page
andadd_submenu_page
both return the page's "hook suffix", which can be used to identify the page with certain hooks. As such, you can use that suffix in combination with the variable hooksadmin_print_styles-{$hook_suffix}
andadmin_print_scripts-{$hook_suffix}
to specifically target these pages.function my_menu() { $menu = add_menu_page( 'Page 1', 'bar', 'something', 'else', 'foo' ); $submenu = add_submenu_page( 'theme_menu', 'Subpage 1', 'Subpage', 'something', 'else', 'foo' ); add_action( 'admin_print_styles-' . $menu, 'admin_custom_css' ); add_action( 'admin_print_styles-' . $submenu, 'admin_custom_css' ); add_action( 'admin_print_scripts-' . $menu, 'admin_custom_js' ); add_action( 'admin_print_scripts-' . $submenu, 'admin_custom_js' ); }
I find this to be a clean method for adding all of this because it's all handled within the one function. If you decide to remove this functionality, simply remove the call to the one function.
-
Cette réponsen'estpastechniquement correcte.le [Codexpour `admin_print_scripts ()`] (http://codex.wordpress.org/Plugin_API/Action_Reference/admin_print_scripts) déclare que "` admin_print_scripts` **ne doitpas être utilisépourmettreen file d'attente des styles ou des scripts **. "La réponse de @TomAugeresten fait labonne,maispas optimale.Il serait avantageux que l'équipe WP ajoute un hook `admin_enqueue_scripts- (hookname)`bien ...This answer is not technically correct. the [Codex for `admin_print_scripts()`](http://codex.wordpress.org/Plugin_API/Action_Reference/admin_print_scripts) states "`admin_print_scripts` **should not be used to enqueue styles or scripts**." The answer by @TomAuger is actually the correct one, although not optimal. It would be beneficial if the WP team added an `admin_enqueue_scripts-(hookname)` hook though...
- 6
- 2014-05-02
- David Gard
-
Ilm'afallu 3jourspourtrouver cette réponse quim'a vraiment aidé :) Merci :)It took me 3 days to find this answer which was really helpful for me :) Thanks :)
- 0
- 2016-11-24
- Asfandyar Khan
-
@DavidGard,vous devriezprobablement regarder ces https://developer.wordpress.org/reference/hooks/admin_print_styles-hook_suffix/,https://developer.wordpress.org/reference/hooks/admin_print_scripts-hook_suffix/@DavidGard, you should probably look at these https://developer.wordpress.org/reference/hooks/admin_print_styles-hook_suffix/ , https://developer.wordpress.org/reference/hooks/admin_print_scripts-hook_suffix/
- 0
- 2018-02-24
- hkchakladar
-
@hkchakladar Mon commentaire apresque quatre ans ... S'iln'estpluspertinent,ajoutez certainement un commentaireplus àjourexpliquantpourquoi.@hkchakladar My comment is nearly four years old... If it's no longer relevant, by all means add a more up to date comment explaining why.
- 1
- 2018-02-24
- David Gard
-
- 2012-12-17
Leproblème avec la réponse @tollmanzest quepuisque vous vous déconnectez des hooks -print-styleset -print-scripts,vous devezgénérer le code HTMLpour charger vos scriptsmanuellement. Cen'estpas optimal,car vousn'obtenezpas labelle dépendanceet lagestion des versionsfournies avec
wp_enqueue_script()
etwp_enqueue_style()
. Celane vouspermetpasnonplus demettre des éléments dans lepied depage si c'est unmeilleurendroitpoureux.Revenons donc à la question du PO: quelest lemeilleurmoyen dem'assurer queje peuxmettre JS/CSSen file d'attente sur despages d'administration spécifiques uniquement?
-
Décrochez l'action "charger - {$my_admin_page}"pourne faire des choses que lorsque c'est lapage d'administration de votreplugin spécifique quiest chargée,puis
-
Décrochez l'action "admin_enqueue_scripts"pour ajouter correctement vos appels
wp_enqueue_script
.
Cela semble unpeupénible,mais c'esten faittrèsfacile àmettreen œuvre. Du haut:
add_action( 'admin_menu', 'add_my_admin_menus' ); // hook so we can add menus to our admin left-hand menu /** * Create the administration menus in the left-hand nav and load the JavaScript conditionally only on that page */ function add_my_admin_menus(){ $my_page = add_menu_page( 'Page Title', 'Menu Title', MY_ADMIN_CAPABILITY, 'menu-slug', 'show_page_content' ); // Load the JS conditionally add_action( 'load-' . $my_page, 'load_admin_js' ); } // This function is only called when our plugin's page loads! function load_admin_js(){ // Unfortunately we can't just enqueue our scripts here - it's too early. So register against the proper action hook to do it add_action( 'admin_enqueue_scripts', 'enqueue_admin_js' ); } function enqueue_admin_js(){ // Isn't it nice to use dependencies and the already registered core js files? wp_enqueue_script( 'my-script', INCLUDES_URI . '/js/my_script.js', array( 'jquery-ui-core', 'jquery-ui-tabs' ) ); } }
The problem with @tollmanz answer is that since you're hooking off of the -print-styles and -print-scripts hooks, you must generate the HTML to load your scripts manually. This is not optimal, since you don't get the nice dependency and versioning that comes with
wp_enqueue_script()
andwp_enqueue_style()
. It also doesn't let you put things in the footer if that's a better place for them.So, back to the OP's question: what's the best way to ensure that I can enqueue JS / CSS on specific admin pages only?
Hook off the "load-{$my_admin_page}" action to only do things when it's your specific plugin's admin page that's loaded, and then
Hook off the "admin_enqueue_scripts" action to properly add your
wp_enqueue_script
calls.
Seems like a bit of a pain, but it's actually very easy to implement. From the top:
add_action( 'admin_menu', 'add_my_admin_menus' ); // hook so we can add menus to our admin left-hand menu /** * Create the administration menus in the left-hand nav and load the JavaScript conditionally only on that page */ function add_my_admin_menus(){ $my_page = add_menu_page( 'Page Title', 'Menu Title', MY_ADMIN_CAPABILITY, 'menu-slug', 'show_page_content' ); // Load the JS conditionally add_action( 'load-' . $my_page, 'load_admin_js' ); } // This function is only called when our plugin's page loads! function load_admin_js(){ // Unfortunately we can't just enqueue our scripts here - it's too early. So register against the proper action hook to do it add_action( 'admin_enqueue_scripts', 'enqueue_admin_js' ); } function enqueue_admin_js(){ // Isn't it nice to use dependencies and the already registered core js files? wp_enqueue_script( 'my-script', INCLUDES_URI . '/js/my_script.js', array( 'jquery-ui-core', 'jquery-ui-tabs' ) ); } }
-
+1 - C'est la voie à suivrepour l'OMI.Les hooksindividuels d'espacement denoms (une action- $ hook) sont utilespour 1 ou 2 actions,mais si vous créez unplugin,vous devrezpeut-êtrefairebeaucoup de choses différentesjuste sur votre (vos)page (s) d'options,ce qui rend cetteméthode vraimentpratique.Engénéral,j'ajoutejuste 1 action au hook `load- $ hook` qui déclenchemafonction` option_page_actions` à laquelleje peux ajouter denombreux autres hooks/filtresetc. Parce que ces actionsne sont appelées que sur lapage de choix,les hooks au-delà de cepointpasbesoin d'utiliser les hooks d'espacement denoms (comme vous l'avezmontré),ce quiestbeaucoupplusefficaceet intuitif.+1 - This is the way to go IMO. The individual namespaced (someaction-$hook) hooks are nice for 1 or 2 actions, but if you're authoring a plugin, you may need to do a lot of different things just on your option page(s) which makes this method really convenient. I usually just add 1 action to the `load-$hook` hook that fires my `option_page_actions` function to which I may add many other hooks/filters etc. Because those actions are only called on the page of choice, hooks beyond that point don't need to use the namespaced hooks (as you have shown), which is much more efficient & intuitive.
- 5
- 2013-06-02
- Evan Mattson
-
Salut,cettefaçonest-elletoujourspriseen charge?load_admin_jsn'appellejamaisHi, is this way still supported? load_admin_js is never calling
- 0
- 2014-03-23
- IAmJulianAcosta
-
Bien sûr,ilesttoujoursprisen charge.Ligne 206 de admin.php.J'y suis depuis 2.6et ilestpeuprobable que cela disparaisse de sitôt (jamais).Sure it's still supported. Line 206 of admin.php. Been there since 2.6, and unlikely to go away any time soon (ever).
- 0
- 2014-03-24
- Tom Auger
-
En regardantma réponsemaintenant,je pense quemettreexplicitementen file d'attentejquery-ui-coreet jquery-ui-tabsesttout àfait superflu,puisque ces scripts sont déjàenregistrés.Il vous suffit de les appeler dans la dépendance.Jemettrai àjourma réponseen conséquence.Looking at my answer now, I believe that explicitly enqueueing jquery-ui-core and jquery-ui-tabs is entirely superfulous, since those scripts are already registered. You just need to call them in the dependency. I'll update my answer accordingly.
- 0
- 2015-04-26
- Tom Auger
-
Fonctionneparfaitement avec WordPress 4.9.6Works perfectly with WordPress 4.9.6
- 0
- 2018-06-18
- ethmz
-
Utilisé dans WPPB (dans une classe) + WP 5.4et celafonctionnetoujours.Used it within WPPB (in a class) + WP 5.4 and it still works.
- 0
- 2020-04-25
- alexwc_
-
- 2012-02-04
Si vous utilisez
get_current_screen()
,vouspouvez détecter lapage que voussurest.Il y a unexemple dans l'article du codex quej'ai lié quimontre comment utiliserget_current_screen()
avecadd_options_page()
,cetteméthodefonctionnerapourn'importe quellepage d'administration.If you use
get_current_screen()
, you can detect what the page you're on is. There is an example in the codex article that I linked which shows how to useget_current_screen()
withadd_options_page()
, this method will work for any admin page. -
- 2015-07-08
Jeme demandais lamême chose.Ilexiste une versionmoderne qui utilise
admin_enqueue_scripts
:add_action('admin_menu', function () { $settingsPage = add_options_page('Settings', 'Mortgage Calculator', 'manage_options', 'mortgagecalculator', function () { echo "<div id='app'></div>"; }); /** * Include the ember admin scripts only on pages where it's needed. */ add_action("admin_enqueue_scripts", function ($hook) use ($settingsPage){ if($hook !== $settingsPage){ return; } // Remove default jQuery since Ember provides its own. wp_dequeue_script('jquery'); wp_enqueue_script('ember-vendor', plugins_url("admin/assets/vendor.js", __FILE__)); wp_enqueue_script('ember-project', plugins_url("admin/assets/mortgage-plugin-ember-admin.js", __FILE__), ['ember-vendor']); wp_enqueue_script('ember-live-reload', "http://localhost:4200/ember-cli-live-reload.js"); }); });
I was wondering the same thing. There's a modern version that uses
admin_enqueue_scripts
:add_action('admin_menu', function () { $settingsPage = add_options_page('Settings', 'Mortgage Calculator', 'manage_options', 'mortgagecalculator', function () { echo "<div id='app'></div>"; }); /** * Include the ember admin scripts only on pages where it's needed. */ add_action("admin_enqueue_scripts", function ($hook) use ($settingsPage){ if($hook !== $settingsPage){ return; } // Remove default jQuery since Ember provides its own. wp_dequeue_script('jquery'); wp_enqueue_script('ember-vendor', plugins_url("admin/assets/vendor.js", __FILE__)); wp_enqueue_script('ember-project', plugins_url("admin/assets/mortgage-plugin-ember-admin.js", __FILE__), ['ember-vendor']); wp_enqueue_script('ember-live-reload', "http://localhost:4200/ember-cli-live-reload.js"); }); });
-
- 2012-09-20
Vouspouvezprendre
@tollmanz
answer ,et développez-le légèrement,permettant également un usage conditionnel ...<₹Example:
/* Add admin pages */ function my_admin_pages(){ $menu = array(); $menu['main_page'] = add_menu_page('Page 1', 'bar', 'something', 'else', 'foo'); $menu['sub_page'] = add_submenu_page('theme_menu', 'Subpage 1', 'Subpage', 'something', 'else', 'foo'); foreach($menu as $key => $value){ if($key == 'main_page'){ /* Print styles on only the main page. */ add_action('admin_print_styles-'.$value, 'print_styles'); } /* Print scripts on all of our admin pages. */ add_action('admin_print_scripts-'.$value, 'print_scripts'); } } add_action('admin_menu', 'my_admin_pages');
You could take
@tollmanz
answer, and expand on it slightly, allowing for conditional usage as well...Example:
/* Add admin pages */ function my_admin_pages(){ $menu = array(); $menu['main_page'] = add_menu_page('Page 1', 'bar', 'something', 'else', 'foo'); $menu['sub_page'] = add_submenu_page('theme_menu', 'Subpage 1', 'Subpage', 'something', 'else', 'foo'); foreach($menu as $key => $value){ if($key == 'main_page'){ /* Print styles on only the main page. */ add_action('admin_print_styles-'.$value, 'print_styles'); } /* Print scripts on all of our admin pages. */ add_action('admin_print_scripts-'.$value, 'print_scripts'); } } add_action('admin_menu', 'my_admin_pages');
-
- 2016-11-14
Comme @mor7ifermentionné ci-dessus,vouspouvez utiliser lafonctionnative de WordPress get_current_screen () . Si vousparcourez la sortie de cettefonction,parexemple:
$current_screen = get_current_screen(); foreach($current_screen as $key => $value) { error_log(print_r($key,1)); }
... vous remarquerez une clé appelée base . J'utilise cecipour détecter sur quellepageje suiset mettreen file d'attente,retirer lafile d'attente comme ceci:
add_action('admin_enqueue_scripts', 'some_hook_function')* ): public function some_hook_function(){ // # only register and queue scripts & styles on POST edit screen of admin $current_page = get_current_screen()->base; if($current_page == 'post' || $current_page == 'page') { wp_enqueue_script('datetimepicker', plugins_url('assets/jquery-ui-timepicker-addon.min.js', __FILE__), array('jquery', 'jquery-ui-datepicker', 'jquery-ui-slider'), '1.9.1', true); wp_enqueue_style( 'jquery-ui-datepicker', plugins_url('assets/jquery-ui.min.css', __FILE__), array(), '1.11.2', 'all'); } else { // # if not on post page, deregister and dequeue styles & scripts wp_dequeue_script('datetimepicker'); wp_dequeue_style('jquery-ui-datepicker'); } }
As @mor7ifer mentioned above, you can use the native WordPress function get_current_screen(). If you loop through the output of this function, e.g.:
$current_screen = get_current_screen(); foreach($current_screen as $key => $value) { error_log(print_r($key,1)); }
... you'll notice a key called base. I use this detect what page I'm on and enqueue, dequeue like so:
add_action('admin_enqueue_scripts', 'some_hook_function')* ): public function some_hook_function(){ // # only register and queue scripts & styles on POST edit screen of admin $current_page = get_current_screen()->base; if($current_page == 'post' || $current_page == 'page') { wp_enqueue_script('datetimepicker', plugins_url('assets/jquery-ui-timepicker-addon.min.js', __FILE__), array('jquery', 'jquery-ui-datepicker', 'jquery-ui-slider'), '1.9.1', true); wp_enqueue_style( 'jquery-ui-datepicker', plugins_url('assets/jquery-ui.min.css', __FILE__), array(), '1.11.2', 'all'); } else { // # if not on post page, deregister and dequeue styles & scripts wp_dequeue_script('datetimepicker'); wp_dequeue_style('jquery-ui-datepicker'); } }
-
- 2019-02-18
Pour yparvenir,vous devez d'abordtrouver lenom de lapage d'administration.Ajoutez
admin_enqueue_scripts
avecwp_die($hook)
et accédez à votrepage deplugin spécifique,vous verrez lenom de lapage.function my_plugin_scripts($hook) { wp_die($hook); } add_action( 'admin_enqueue_scripts', 'my_plugin_scripts' );
settings_page_plugging_info
Copiezmaintenant lenom de lapageet utilisez-lepour charger les scripts sur lapage spécifique.
function my_plugin_scripts($hook) { if ( 'settings_page_plugging_info' != $hook ) { return; } wp_enqueue_script( 'my_custom_script', plugins_url('js/file.js', __FILE__)); } add_action( 'admin_enqueue_scripts', 'my_plugin_scripts' );
To make it, you have to find the admin page name first. Add
admin_enqueue_scripts
withwp_die($hook)
and go to your specific plugin page, You will see the page name.function my_plugin_scripts($hook) { wp_die($hook); } add_action( 'admin_enqueue_scripts', 'my_plugin_scripts' );
settings_page_plugging_info
Now copy the page name and use it in condition to load the scripts on the specific page.
function my_plugin_scripts($hook) { if ( 'settings_page_plugging_info' != $hook ) { return; } wp_enqueue_script( 'my_custom_script', plugins_url('js/file.js', __FILE__)); } add_action( 'admin_enqueue_scripts', 'my_plugin_scripts' );
-
- 2013-07-05
De la documentation :
admin_print_scripts
principalement utilisépourfaire écho aujavascripten ligne.admin_print_scripts
ne doitpas être utilisépourmettreen file d'attente des styles ou des scripts sur lespages d'administration.Utilisezplutôtadmin_enqueue_scripts
. "Idem avec
admin_print_styles
.From the documentation:
admin_print_scripts
mainly used to echo inline javascript.admin_print_scripts
should not be used to enqueue styles or scripts on the admin pages. Useadmin_enqueue_scripts
instead."Same with
admin_print_styles
.-
Regardez ces https://developer.wordpress.org/reference/hooks/admin_print_scripts-hook_suffix/,https://developer.wordpress.org/reference/hooks/admin_print_styles-hook_suffix/Look at these https://developer.wordpress.org/reference/hooks/admin_print_scripts-hook_suffix/ , https://developer.wordpress.org/reference/hooks/admin_print_styles-hook_suffix/
- 0
- 2018-02-24
- hkchakladar
-
- 2015-01-11
add_action( 'admin_menu', 'add_my_admin_menus' ); function add_my_admin_menus() { $GLOBALS['my_page'] = add_menu_page( 'Page Title', 'Menu Title', MY_ADMIN_CAPABILITY, 'menu-slug', 'show_page_content'); add_action( 'admin_enqueue_scripts', 'enqueue_admin_js'); } function enqueue_admin_js($hook) { if($GLOBALS['my_page'] === $hook) { wp_enqueue_script( 'jquery-ui-core' ); wp_enqueue_script( 'jquery-ui-tabs' ); // Isn't it nice to use dependencies and the already registered core js files? wp_enqueue_script( 'my-script', INCLUDES_URI . '/js/my_script.js', array( 'jquery-ui-core', 'jquery-ui-tabs' ) ); } }
add_action( 'admin_menu', 'add_my_admin_menus' ); function add_my_admin_menus() { $GLOBALS['my_page'] = add_menu_page( 'Page Title', 'Menu Title', MY_ADMIN_CAPABILITY, 'menu-slug', 'show_page_content'); add_action( 'admin_enqueue_scripts', 'enqueue_admin_js'); } function enqueue_admin_js($hook) { if($GLOBALS['my_page'] === $hook) { wp_enqueue_script( 'jquery-ui-core' ); wp_enqueue_script( 'jquery-ui-tabs' ); // Isn't it nice to use dependencies and the already registered core js files? wp_enqueue_script( 'my-script', INCLUDES_URI . '/js/my_script.js', array( 'jquery-ui-core', 'jquery-ui-tabs' ) ); } }
J'ai deuxfonctions simples qui chargent des chosesen utilisant
wp_enqueue_style()
etwp_enqueue_script()
,quelque chose comme ceci:...et quelquespages d'administration,créées avec
add_menu_page()
et < a href="http://codex.wordpress.org/Function_Reference/add_submenu_page">add_submenu_page()
Comment chargermes deuxfonctions uniquement sur cespages?
En cemoment,j'utilise:
Maisil chargemesfichiers sur chaquepage d'administration,ce quin'estpas dutout agréable.
Puis-je lefaire via une simple ligne dans
functions.php
ou dois-je lesmettreen file d'attente dansmespages séparément (jepréfèrefortement lapremière option,carje devraismodifierbeaucoup d'administrateurs -page-creation-functions).Merci!