1

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?

2
  • 3
    I assume you're after the $post global? If so, you need to define it as global... Apr 23, 2012 at 23:53
  • 2
    A corollary answer: From what it sounds like you're planning, you should strongly consider making this a plugin rather than stuff in functions.php. See: justintadlock.com/archives/2011/02/02/…
    – mrwweb
    Apr 24, 2012 at 1:10

2 Answers 2

3

Globals aren't passed into functions. You have to declare them.

Change this:

function test() {
   return $post->ID; //or echo $post->ID;
}

...to this:

function test() {
   global $post;
   return $post->ID; //or echo $post->ID;
}
4
  • I was checking globals before, and found out that test() works perfectly in page.php but returns 'Call to undefined function test()' within header.php or footer.php? What's the issue? Actually I need to use it in the header. Apr 24, 2012 at 1:53
  • Check for a syntax error, or misspelled function, or something. The functions.php file gets parsed well before any of the template files are loaded. Also, template-part files like header.php are included by template files like page.php, so there's no chance that the function isn't defined. Apr 24, 2012 at 2:08
  • Thanks, no syntax errors though. I guess it just doesn't work used in file that is being included within functions.php. Apr 24, 2012 at 18:00
  • Not sure I understand that last comment. header.php doesn't get included within functions.php. Apr 24, 2012 at 18:51
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.