Getting ‘Call to undefined function wp_get_current_user()’ error when do_action is used

Note that this question was created to avoid global $plugin_name;


I am writing a WordPress (WP 3.6) plugin and I am getting

Read More

wp_get_current_user() in /var/www/wordpress/wp-includes/capabilities.php on line 1281, referer: http://10.1.1.6/wp-admin/admin.php?page=mhomepage/mhomepage_admin_menu.php if I use this code

$plugin_name='mhomepage';

// Hook for adding admin menus
add_action('admin_menu', 'add_plugin_admin_page', 10, 1);
do_action('admin_menu', $plugin_name.'/mhomepage_admin_menu.php');

// add_action('admin_menu', 'add_plugin_admin_page');

function add_plugin_admin_page($plugin_name) {
    // global $plugin_name;

    //must check that the user has the required capability 
    if (!current_user_can('manage_options'))
    {
      wp_die( __('You do not have sufficient permissions to access this page.') );
    }

    add_menu_page( 'mHomePage', 'mHomePage', 'manage_options', 'mhomepage/mhomepage_admin_menu.php', '', '', 6 );
    // add_menu_page( 'mHomePage', 'mHomePage', 'manage_options', $plugin_name, '', '', 6 );
}

where the mhomepage_admin_menu.php looks like

<?php

    echo "Plugin menu page";

?>

but in case I use add_action('admin_menu', 'add_plugin_admin_page');
in the above code instead of

// add_action('admin_menu', 'add_plugin_admin_page', 10, 1);
// do_action('admin_menu', $plugin_name.'/mhomepage_admin_menu.php');

everything works fine? Could someone explain what and why is happening and what the solution would be? I want to use do_action to pass the argument to add_plugin_admin_page function.

I found this answer https://stackoverflow.com/a/6127607/250422 but I am not sure if it applies to my case too and I really don’t understand what I would be supposed to do.

Related posts

Leave a Reply

1 comment

  1. Try this instead if you want to pass arguments to your function

    // Hook for adding admin menus
    add_action('admin_menu', 'add_plugin_admin_page', 10, 1);
    do_action('admin_menu', $plugin_name);
    

    The first line you’re creating an action that you have told to hook into a WordPress function. The second line that action with the arguments.

    do_action()

    EDIT

    Since it may or may not be wise to add arguments to default WordPress action hooks. Let’s try and separate it in a different way.

    Create your own hook

    add_action( 'admin_menu', 'add_plugin_admin_page', 10, 1 );
    add_action( 'plugin_admin_page', 'plugin_admin_page_arguments' );
    
    function plugin_admin_page_arguments() {
      $plugin_name = 'Hello World'; // Your argument
      do_action('plugin_admin_page', $plugin_name);
    }
    

    Then your admin page function and it’s argument

    function add_plugin_admin_page($plugin_name) {
      echo $plugin_name;
    }
    

    This isn’t tested but it should give you an idea