Trying to use add_action and do_action with parameters

You are using it wrong.

  • add_action: attachs a function to an action hook. In your code, you are attaching alter_item funtion to admin_menu action hook. So, when admin_menu action happens, alter_item function is executed. According to codex, no parameters are passed to functions attached to admin_menu. So, the parameters your are trying to use in alter_item are not valid.

  • do_action: invokes all functions attached to an action hook. In your code, you are invoking all functions attached to alter_item action hook. alter_item action hook would be a custom action hook, as it is not in WP core, but currently in your code there is zero functions attached to this action, so nothing will happen with your do_action('alter_item'....

The correct way to attach a function to admin_menu is:

function alter_item() {
    //Do whatever you want
}
//The priority argument (10 the code bellow) is optional.
add_action( 'admin_menu', 'alter_item', 10 );

The correct way to define custom actions:

do_action('alter_item', 'my-user', 'plugins.php', false);

Then you can attach functions to alter_item action like this:

add_action( 'alter_item', 'alter_item_attached_function', 10, 3 );

function alter_item_attached_function( $user, $items, $action ) {
     //Now $user, $items and $action will be 'my-user', 'plugins.php' and false
}

If you want to pass information to core actions, you can:

  • use the valid parameters for each action. Refer to official documentation of each action.
  • define global variables, use options, transiets or custom objects properties/methods, so you can use that information in differents places of your code. Example.
  • Use PHP anonymous functions with use keyword.

Example using use keyword:

$user="my-user";
$items="plugins.php";
$action = false;

add_action( 'admin_menu', function() use ($user, $items, $action) {
    global $current_user, $menu;
    get_currentuserinfo();
    switch ($action) {
        case false:
            if ($current_user->user_login == $user) {
                remove_menu_page ($items);
            }
        break;

        case true:
            if ($current_user->user_login == $user) {
                remove_menu_page ($items);
            }
        break;
    }
} );

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)