I would like to add a button to do a customised task when clicked on it, I am going to get 'term_id' of the current menu and do a rest call to somewhere else. I would like to do it with a hook, do not want to write code in WP core. I could not find an appropriate hook to add the button.
I checked the source code of this section (wp-admin/nav-menus.php) and there aren't any hooks in that exact location that you can use for this.
However, you can use some jQuery sorcery to append your custom button exactly where you want it, retrieve the ID of the current menu and do your REST call via AJAX:
<?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: [email protected]
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Copyright 2018 Hector Cabrera ([email protected])
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');