filters - How to call a function or method that is Namespaced using another plugin

admin2025-06-02  2

I'm using an action from one plugin that needs to call a function from another plugin. That function is name spaced.

Typically, I would use something like:

add_action( 'hook_name', 'function_name' );

But the plugin's function is Namespaced and/or object-oriented, so I'm not sure how to reference the function in that case.

I.e., how do I reference that specific function?

I'm using an action from one plugin that needs to call a function from another plugin. That function is name spaced.

Typically, I would use something like:

add_action( 'hook_name', 'function_name' );

But the plugin's function is Namespaced and/or object-oriented, so I'm not sure how to reference the function in that case.

I.e., how do I reference that specific function?

Share Improve this question asked Mar 12, 2019 at 16:52 Joe FletcherJoe Fletcher 1307 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3

add_action's second parameter is a callable, it can accept a string (like what you did in the example) or an array of class-instance and function name.

For example, if you want to call a method get_age() from Person class, you can do this:

$person = new Person();
add_action( 'hook_name', array($person , 'get_age') );

Here is generic code that worked for me. If anyone wants a real-life example, please let me know.

This creates a function that calls the plugin's function assuming the namespace is "Custom"

add_action( 'hook_name', 'my_custom_function_name' );
function my_custom_function_name() {
    // Check if "Custom Plugin" installed and activated
    if ( did_action( 'plugin/loaded' ) ) {
        // call the Plugin's function (clear_cache function example here)
        \Custom\Plugin::instance()->files_manager->clear_cache();
    }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748814215a313943.html

最新回复(0)