I have a weird problem when trying to set a cookie with the init hook (I must say I’m new on WP)
This is the code that’s not working:
plugin.php file:
...
require_once( PLUGIN_DIR . 'class.plugin.php' );
add_action( 'init', array( 'Plugin', 'init_hooks' ) );
...
class.plugin.php file:
class Plugin {
private static function init_hooks() {
...
add_action('init',array('Plugin','setCookieAction'));
...
}
public static function setCookieAction(){
setcookie('mycookie', $_GET['myCookie'], time() + 3600, COOKIEPATH, COOKIE_DOMAIN);
}
}
However, if I modify the class to this:
class.plugin.php
class Plugin {
private static function init_hooks() {
...
setcookie('mycookie', $_GET['myCookie'], time() + 3600, COOKIEPATH, COOKIE_DOMAIN);
...
}
}
The cookie is being set.
Use an earlier hook to set up the actions that need to run on init:
add_action( 'plugins_loaded', array( 'Plugin', 'init_hooks' ) );