2
votes

I am trying to add a custom button to the WordPress dashboard by iniating it via a custom created theme plugin, not the functions.php file.

I've tried using the add_menu_page() method https://developer.wordpress.org/reference/functions/add_menu_page/ but I think I do not fully understand it as it is not working for me at all:

<?php

add_action('admin_menu', 'mt_add_pages');

function mt_add_pages() {
    add_menu_page( 'Custom Admin Page Title', 'Custom Menu Title', 'manage_options', 'custom_admin_page_slug', 'pg_building_function','',3 );
}

function mt_toplevel_page() {
    echo "<h2>" . _( 'page contents for the menu' ) . "</h2>";
}

Besides, I want to be able to create a link straight on the button to go to custom internal/external URL (target='_blank') - not just have an admin page created within the dashboard when it is clicked on.

Am I doing anything wrong? Would I be able to use this method to do this?

1

1 Answers

2
votes

You have an error on add_menu_page, the callback is pg_building_function but the function you're showing is mt_toplevel_page.

One option is to redirect the page instead of printing any content:

add_action('admin_menu', 'mt_add_pages');

function mt_add_pages() {
    add_menu_page( 'Custom Admin Page Title', 'Custom Menu Title', 'manage_options', 'custom_admin_page_slug', 'pg_building_function','',3 );
}

function pg_building_function() {
    wp_redirect( 'https://google.com' );
    exit;
}

Another one is to use JavaScript:

function pg_building_function() {
    echo "<script>window.open('https://google.com');</script>";
}

Finally, some jQuery to modify the menu attributes:

add_action( 'admin_menu', 'mt_add_pages' );
add_action( 'admin_head', 'redirect_custom_menu' );
function mt_add_pages() {
    add_menu_page( 'My Menu', 'My Menu', 'manage_options', 'custom_admin_page_slug', __return_null,'',3 );
}
function redirect_custom_menu(){
    ?>
    <script type="text/javascript">
        jQuery(document).ready( function($) {   
            $('a.toplevel_page_custom_admin_page_slug').attr('href','https://google.com').attr('target','_blank');  
        });
    </script>
    <?php
}