I try to create an array of years, which is avaible in my template-files and in at least one other function in the functions.php.
function get_the_years()
{
global $year_arr = range(2001, date('Y'));
return $year_arr;
}
Then I want to use it in a function, which creates a term for every year in the custom taxonomy ‘year’.
function create_year_terms() {
foreach($year_arr as $value){
$term = term_exists($value, 'year');
if ($term !== 0 && $term !== null) {
echo $value . ' category exists!';
}
else { wp_insert_term(
$value, // the term
'year', // the taxonomy
array(
'description'=> 'The name of a year',
'slug' => $value )
);
echo'term '. $value . ' created';
}
}
}
And trying to attach this function to the wp_login hook
add_action('wp_login', 'create_year_terms');
I tried to make my hoeworks and I guess I understand “something” but I’m a bit scared to kill something by putting wrong stuff in my functions.php, so please excuse my question.
In order to access a variable defined in the
global
scope you must reference it with theglobal
keyword wherever you want to call it again.In your case, the function
create_year_terms()
must call theglobal $year_arr
within its scope.Also, you can always get your variable in the
global
scope by using the$GLOBALS
array with the name of your variable as thekey
, as such:Update
Regarding your hook decision: First of all, it is best practice to put this kind of code in a plug-in rather than in your theme functions. Second of all, hook it on
init
; or register an activation hook for your plugin and then perhaps use wp_schedule_event with a custom interval of one year.â¦but then again, is this really necessary?
Firstly, you have to define a global variable in the scope, where you want to have access to it, meaning outside your functions (and maybe even outside the class – if you have one.
Secondly, as far as I know, you have to first ‘render’ a variable global, and then, in a new line, set its value:
Inside the functions, you have to state the variable again as global before you use it. Otherwise it’d be just a local variable with the same name as the global (but not yet known) variable from the ‘outside’.
And what is it exactly that you want to do with the function? Do you know about the hook?
wp_login
is deprecated – usewp_signon
. But I don’t get what you’re willing to do…