根据当前管理页面有条件地加载脚本

时间:2017-08-05 作者:Toniq

我只在插件页面上使用load将脚本排队。

https://developer.wordpress.org/reference/hooks/load-page_hook/

add_action("admin_menu", "sap_admin_menu");
function sap_admin_menu(){

    $menu = add_menu_page("Sticky Audio Player Player manager", "Sticky Audio Player", "manage_options", "sap_player_manager", "sap_player_manager_page", \'dashicons-playlist-audio\');

    $submenu = add_submenu_page("sap_player_manager", "Sticky Audio Player Player manager", "Player manager", "manage_options", \'sap_player_manager\', "sap_player_manager_page");   
    $submenu2 = add_submenu_page("sap_player_manager", "Sticky Audio Player Playlist manager", "Playlist manager", "manage_options", \'sap_playlist_manager\', \'sap_playlist_manager_page\');

    add_action( \'load-\' . $menu, \'sap_admin_enqueue_scripts\' );
    add_action( \'load-\' . $submenu, \'sap_admin_enqueue_scripts\' );
    add_action( \'load-\' . $submenu2, \'sap_admin_enqueue_scripts\' );

}
这很好,但是我想知道如何检测我当前在哪个页面上,以便我可以在sap\\u admin\\u enqueue\\u scripts函数中将不同的脚本排队:

function sap_admin_enqueue_scripts() {

    //I need to detect page here

    if ( is_page( \'sap_player_manager\' ) ) {//this doesnt work


    }
我尝试使用is\\U页面,但无法正常工作。

3 个回复
SO网友:Nuno Sarmento

你可以这样做

add_action( \'admin_menu\', \'my_admin_menus\' ); 

function 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\' ) );
  }
}

SO网友:ClemC

What about get_current_screen()?

$screen = get_current_screen();

if ( \'sap_player_manager\' === $screen->id ) {

}
SO网友:hwl

调查get_current_screen();

codex的一些注释:

大多数管理页面上都定义了此函数,但并非所有页面都定义了此函数。因此,在某些情况下is_admin() 将返回true,但正在尝试调用get_current_screen() 将导致致命错误,因为它未定义。一个已知的示例是wp admin/customize。php。

还有一个current_screen 钩住另一种方法。

两者都提供了WP_Screen. 例如:

WP_Screen Object {
    ["action"] => string(0) ""
    ["base"] => string(4) "post"
    ["columns":"WP_Screen":private] => int(0)
    ["id"] => string(12) "someposttype"
    ["in_admin":protected] => string(4) "site"
    ["is_network"] => bool(false)
    ["is_user"] => bool(false)
    ["parent_base"] => NULL
    ["parent_file"] => NULL
    ["post_type"] => string(12) "someposttype"
    ["taxonomy"] => string(0) ""
    ["_help_tabs":"WP_Screen":private] => array(0) { }
    ["_help_sidebar":"WP_Screen":private] => string(0) ""
    ["_options":"WP_Screen":private] => array(0) { }
    ["_show_screen_options":"WP_Screen":private] => NULL
    ["_screen_settings":"WP_Screen":private] => NULL
}

结束

相关推荐