插件Add_action和Add_Menu_Page

时间:2019-10-24 作者:Toniq

我正在使用此代码为我的插件创建菜单。这很有效。

我的问题是:在foo\\u admin\\u enqueue\\u scripts回调中包含一些php页面和将一些脚本/样式排队与在add\\u menu\\u page/add\\u submenu\\u page回调中包含它们有什么区别?

function foo_admin_menu(){

    $menu = add_menu_page(\'Player manager\', \'Foo Audio Player\', FOO_CAPABILITY, \'foo_settings\', \'foo_settings_page\', \'dashicons-playlist-audio\');

    $submenu = add_submenu_page(\'foo_settings\', __(\'Foo Audio Player\', FOO_TEXTDOMAIN), __(\'Settings\', FOO_TEXTDOMAIN), FOO_CAPABILITY, \'foo_settings\', \'foo_settings_page\');   
    $submenu2 = add_submenu_page(\'foo_settings\', __(\'Foo Audio Player\', FOO_TEXTDOMAIN), __(\'Player manager\', FOO_TEXTDOMAIN), FOO_CAPABILITY, \'foo_player_manager\', \'foo_player_manager_page\');    

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

}

function foo_settings_page(){

    //1. include php page and script here?

    include("settings.php");

    wp_enqueue_script(\'enqueue something here\')

}

function foo_player_manager_page(){

    ...

}

function foo_admin_enqueue_scripts() {

    //2. or include php page and script here?

    wp_enqueue_script(\'jquery\');
    wp_enqueue_media();

    wp_enqueue_style(\'foo\', plugins_url(\'/css/admin.css\', __FILE__));   
    wp_enqueue_script(\'foo\', plugins_url(\'/js/admin.js\', __FILE__), array(\'jquery\'));

}

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

主要区别在于(link) 或脚本标记位于源中,或资源是否加载到head 或页脚。

带有add_menu_page()/add_submenu_page() 像您的foo_settings_page(), 样式/脚本文件将加载到body (交割前body 标记),因为head 在回调(foo_settings_page()) 被称为:

<body>
    ...
    the content of your plugin page (added through foo_settings_page())
    ...
    ...
    <!-- The style/script file would be loaded here, in the footer. -->
</body>
foo_admin_enqueue_scripts() 这是一个load-<page hook> 回调时,样式/脚本文件将加载到head &mdash;但对于脚本,它可以在页脚中;检查第五个参数wp_enqueue_script():

<head>
    ...
    <!-- The style/script file would be loaded here, unless if the *script* is set
    to be loaded in the footer. -->
    ...
</head>
head 和页脚中的脚本文件&mdash;虽然在现代,剧本may be put in the head.

相关推荐