0

我想添加一个按钮以在单击它时执行自定义任务,我将获取当前菜单的“term_id”并对其他地方进行休息调用。我想用钩子来做,不想在WP核心中编写代码。我找不到合适的钩子来添加按钮。

WordPress 外观菜单

4

1 回答 1

1

我检查了本节的源代码(wp-admin/nav-menus.php),在那个确切的位置没有任何钩子可以用来做这个。

但是,您可以使用一些 jQuery 魔法将自定义按钮准确地附加到您想要的位置,检索当前菜单的 ID 并通过 AJAX 进行 REST 调用:

<?php
/*
Plugin Name: WP Admin Menu Custom Button
Description: Adds a custom button to the Menu Administration page.
Author: Hector Cabrera
Author URI: https://cabrerahector.com
Author Email: me@cabrerahector.com
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html

Copyright 2018 Hector Cabrera (me@cabrerahector.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

if ( !defined( 'WPINC' ) ) {
    die();
}

function wp54428_add_custom_button_to_menu_screen() {

    $screen = get_current_screen();

    if (
        isset( $screen->id ) 
        && 'nav-menus' == $screen->id
    ) {
        ?>
        <script>
            jQuery(function($) {

                // Let's use the Save menu button as a reference point for all of our actions
                var save_menu_button = $("#save_menu_header");

                // We're currently seeing the Edit Menu screen, so let's do our thing
                if ( !save_menu_button.closest('.menu-edit').hasClass('blank-slate') ) {

                    // Append our custom button next to the Save/Create button
                    save_menu_button.before('<a href="#" id="my_custom_button" class="button button-primary button-large">My Custom Button</a> ');

                    // Click handler for our custom button
                    save_menu_button.parent().on("click", "#my_custom_button", function(e){
                        e.preventDefault();

                        // Test to check that we are getting the menu ID correctly
                        alert( save_menu_button.closest('.menu-edit').find("#menu").val() );

                        // @TODO
                        // Send the ID to the REST API via AJAX

                    });

                }

            });
        </script>
        <?php
    }

}
add_action('admin_footer', 'wp54428_add_custom_button_to_menu_screen');
于 2018-04-04T13:57:31.703 回答