Sorry for being such a noob. I'm sure this is an easy question for most. I'm trying to register activation and deactivation hooks for my plugin. In the docs, they warn about the activation callback not having access to global variables:
If you’re using global variables, you may find that the function you pass to register_activation_hook() does not have access to global variables at the point when it is called, even though you state their global scope within the function like this:
...
The main body variables are therefore in the scope of the activate_plugin()
function and are not global unless you explicitly declare their global scope:
global $myvar;
$myvar = 'whatever';
function myplugin_activate() {
global $myvar;
echo $myvar; // this will be 'whatever'
}
register_activation_hook( __FILE__, 'myplugin_activate' );
So, following that advice, I set up my code like this:
global $post_id;
$post_id = 0;
function install_xxx() {
global $post_id;
$post = array(
'post_title' => __( 'Thank You', 'xxx' ),
'post_content' => __( 'Lorem ipsum dolor.', 'xxx' ),
'post_status' => 'publish',
'post_name' => 'thank-you',
'post_type' => 'page'
);
$post_id = wp_insert_post( $post, true );
error_log('Inserted page: ' . $post_id);
}
function uninstall_xxx() {
global $post_id;
error_log('Removing page: ' . $post_id);
$post = wp_delete_post( $post_id, true );
}
register_activation_hook( __FILE__, 'install_xxx' );
register_deactivation_hook( __FILE__, 'uninstall_xxx' );
But in my logs, it will echo something like:
- Inserted page: 109
- Removing page: 0
And, of course, the page isn't removed.
In other words, the global $post_id
isn't being updated. Any clue what I'm doing wrong?
global
keyword. Remember, PHP and WordPress are loaded from a blank slate on every request, nothing is carried over, and everything is loaded from scratch. Global variables let you share variables across scopes within a single request, but they are not persisted. If you want to store the page ID on one request, and retrieve it on another, you need to save that ID in the databaseadd_option()
the preferred way to persist this value? or direct DB manipulation?