[wp-hackers] Hook being called twice on activate, once on deactivate

mark waterous mark at watero.us
Thu Oct 29 19:24:00 UTC 2009


I was hoping somebody on here might be able to explain the following strange
behavior I stumbled across.

 

I've been working on a plugin that during activation needs to create some
tables. The table names are stored in constants for use in various locations
around the plugins codebase, and are defined ala;

 

define( 'MYPLUGIN_TABLE_WHATEVER', $wpdb->prefix . 'table_whatever' );

 

Which works fine everywhere else in the code, returning the desired
'wp_#_table_whatever' string I need. Right up until the constant is used
from inside an activation callback, at which point it drops the
$wpdb->prefix, and I wind up with tables called only 'table_whatever' (no
prefix). So I wrote a quick'n'dirty to try and discern what was occurring;

 

<?php /*

Plugin Name: WPDB Object Test

Description: If you only knew.

Version: 0.1

*/

 

define( 'WPDB_TEST_TABLE', $wpdb->prefix . 'table_name' );

 

$outside_data = WPDB_TEST_TABLE;

 

function wpdb_test_activate( $outside_data ) {

                global $wpdb;

 

                $file = dirname( __FILE__ ) . '/test.log';

 

                $data = 'Outside: ' . $outside_data . "\n";

                $data .= 'Constant: ' .WPDB_TEST_TABLE . "\n";

                $data .= 'Inside: ' . $wpdb->prefix . "table_name\n\n";

 

                $fp = @fopen( $file, 'a' );

                if ( $fp )

                                fwrite( $fp, $data );

                fclose( $fp );

}

 

register_activation_hook( __FILE__, call_user_func( 'wpdb_test_activate',
$outside_data ) );

?>

 

This resulted in behavior I wasn't expecting - it would appear that the hook
runs twice on activation. The first run strips $wpdb->prefix, the second
time it doesn't. It also runs the activation hook again on deactivation.
Should it be doing that? The actual plugin has a deactivation hook of
course, but I wasn't expecting it to run the activation hook in absence of
this.

 

My test.log file looks like this, though you could run it for yourself to be
sure (the first two groups are from activation, the third from
deactivation):

 

<test.log>

Outside: table_name

Constant: table_name

Inside: wp_3_table_name

 

Outside: wp_3_table_name

Constant: wp_3_table_name

Inside: wp_3_table_name

 

Outside: wp_3_table_name

Constant: wp_3_table_name

Inside: wp_3_table_name

</test.log>

 

(sorry about the long post, and this apology that makes it even longer)

 

--

Mark Waterous

 <http://mark.watero.us/> http://mark.watero.us/ ( <mailto:mark at watero.us>
mark at watero.us) 

 



More information about the wp-hackers mailing list