Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress : add_action : why the second parameter is an array instead of a function name

Tags:

php

wordpress

I am trying to create a wordpress plugin, I found one plugin which use oops concepts, my question is why the second parameter in the add_action function is an array instead of a function name

add_action('admin_menu', array(&$this, 'my_menu'));

my_menu is a function in the same class, please help me

Thanks

like image 497
Thomas John Avatar asked Jun 01 '11 16:06

Thomas John


People also ask

Can I pass arguments to my function through Add_action?

Yes you can! The trick really is in what type of function you pass to add_action and what you expect from do_action.

Which is default value of $priority parameter in Add_action () function?

$priority (optional) – order in which the callback will be run. Lower number is associated with earlier execution. $accepted_args (optional) – the number of args that will be passed to the callback. Default is 1.

What is use of Add_action in WordPress?

The add_action function is arguably the most used function in WordPress. Simply put, it allows you to run a function when a particular hook occurs.

How do you add a function in WordPress?

To make it useful, you need to add your custom function to the PHP file and then upload the folder to the plugin directory of your WordPress site, usually wp-content/plugins/. If you need to add new WordPress functions, you can simply overwrite the old version with your changes.


2 Answers

@Thomas John, you are correct about second argument in add_action also in wordpress org not mentioned anything about this so now, let me know you, we can pass array as second argument array($this,'method').

Description: when object creates of class then constructor automatically calls and your action performs.

WHY IT REQUIRES in wordpress how to create or initialize the class in add_action method in short add_action referencing a class check below example

class Myclass{
 public function __construct() {


add_action( 'plugins_loaded', array( $this, 'load_plugin_textdomain' ) );

}
}

Referencing a class using add_action().

like image 139
Hiren Kubavat Avatar answered Sep 22 '22 00:09

Hiren Kubavat


Because the second argument needs to be a callback. (and add_action internally uses call_user_func_array).

For functions we can just pass its name as a string but we can't do that with object methods, can we?

So an array is passed with 2 elements, first the object and second the method to call:-

array( $object, 'method' )

Oh and you can safely remove that useless '&', PHP4 days are gone now.

like image 41
Salman von Abbas Avatar answered Sep 22 '22 00:09

Salman von Abbas