Reputation: 10066
I have the following code:
class IPT_FSQM_Form_Creation_Hook {
public function __construct() {
add_action( 'ipt_fsqm_form_created', array( $this, 'hook_into_form_creation' ), 10, 1 );
}
function hook_into_form_creation( $data ) {
// Global config and db variables
global $wpdb, $ipt_fsqm_info;
$wpdb->insert( $ipt_fsqm_info['form_table'], array(
'name' => 'I did this',
) );
}
}
The hook created in the plugin is as follows:
$return_id = $wpdb->insert_id;
do_action( 'ipt_fsqm_form_created', $return_id, $this );
My custom hook doesn't get triggered how I have it. I know it doesn't get triggered because nothing gets inserted into the database. When I change the code to the following it inserts the data but then I don't have access to any of the data in the $this
variable:
add_action( 'ipt_fsqm_form_created', 'hook_into_form_creation' );
function hook_into_form_creation( $data ) {
// Global config and db variables
global $wpdb, $ipt_fsqm_info;
$wpdb->insert( $ipt_fsqm_info['form_table'], array(
'name' => 'I did this',
) );
}
How can I get the data in $this
and still get access to my hook?
Upvotes: 0
Views: 252
Reputation: 5062
Turns out the problem was that the class was not being initialized and therefore the function never attached to the action.
I think you're approaching this the wrong way. The $this
variable that is available within non-static methods of a class always points to the current class's instance. So using $this
within your method would actually point at the IPT_FSQM_Form_Creation_Hook
class instance, and not at the instance of the class that fired the action.
Since you're not using this class for anything else, there's not much of a point in making that class. Instead you can make a regular function and attach that to the action, just like you already did. There's only one difference though:
add_action( 'ipt_fsqm_form_created', 'hook_into_form_creation', 10, 2 );
function hook_into_form_creation( $data, $object ) {
// Global config and db variables
global $wpdb, $ipt_fsqm_info;
$wpdb->insert( $ipt_fsqm_info['form_table'], array(
'name' => 'I did this',
) );
}
Note the last parameter of add_action()
: 2. This defines how many parameters your callback function expects and defaults to 1. Also note that I've now added an $object
parameter to your function. Use this as you would've used $this
in your function - it will be the instance of the other plugin's class.
Note that certain properties and methods of $object
might not be accessible for you(such as private/protected methods and properties) and there isn't really anything you can do, since your function will never be part of the other plugin's class scope.
Upvotes: 1