I want to do some (sometimes really complex) stuff on my pages based on pages/posts IDs’, Settings API, etc.
Now I’ve all my functions written directly within page.php file, but I don’t want it to leave it this way – it’s really messy and it’s hard to control everything. I’d love to have separate files for each function and load them from there. But there’s a huge issue:
functions.php
function test() {
return $post->ID; //or echo $post->ID;
}
page.php
<?php
test();
?>
Of course test() returns nothing.
Is there any way to overcome that, or my approach is stupid once again? If yes – how should I store my functions outside of core theme files?
Globals aren’t passed into functions. You have to declare them.
Change this:
…to this:
a few things.
first, as Chip stated, globals need to be declared with the private scope of a function.
second, I suspect your Page.php code wouldn’t ‘print’ anything because the function returns a value but doesn’t echo it.
third, when designing your pages and functions, you need to keep in mind which variables are going to change according to circumstance. it might not be practical to depend of WP’s global variables all of the time. instead, pass the variables as parameters in your functions. if planned carefully, it will be more reliable and allow you to do more with the same functions.
cheers,
Gregory