将自定义按钮添加到Wordpress菜单管理页面

时间:2018-04-04 13:15:10

标签: wordpress menu wordpress-hook

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

Wordpress Appearence Menu

1 个答案:

答案 0 :(得分: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');