I believe this is because templates are now wrapped in a function call to limit the scope of any vars defined – correct me if I’m wrong, can’t find any docs.
Does anyone have a comment here?
Is it possible to use a plugin to have pages “share” data? Or is there a better solution?
Any pointers to docs? or an example?
Hello convert, if you’ve got vars in functions.php or a plugin that you want to access in a template, you need to add a global var declaration for that var to the template, and should work.
Figured it out myself, can’t see this in any WP docs?! *forum tumbleweed*
Thanks. I’ve tried that but I must be doing something wrong.
Let me give it another whack…
Okay, I’m still missing something basic. I’ll admit it’s probably PHP rather than WordPress, but here’s my situation.
functions.php:
global $testvar;
add_action( 'hook_defined_in_plugin1', 'my_process_plugin1_data');
I’ve written “plugin2.php” and installed/activated it. Its code contains
global $testvar;
function my_process_plugin1_data( --args as from plugin1-- )
{
global $testvar;
$testvar="this is in the data processing function";
}
Finally in a PHP template file for a page displayed after my_process_plugin1_data executes, I have
global $testvar;
echo "<br />Confirm var value===".$testvar."===</br>";
but $testvar shows up as an empty string.
I’ve confirmed the hook/action works — in the template file I can retrieve a cookie that’s set by the my_process_plugin1_data function. But I just can’t seem to get the function and the page communicating through a variable.
I’ve searched the docs and the book “WordPress Plugin Development” — but nothing jumps out as the step-by-step way to set up this communication.
And commenting out either one of the global’s in the plugin2.php file makes no difference.
I think you will need to actually set/declare $testvar outside of the function in plugin2.php –
$testvar = 'test';
Eg my usage is like this: in functions.php I have:
// global value, incremented for multiple search form ids
$SEARCH_ID=1;
Then in searchform.php:
<?php global $SEARCH_ID; ?>
<form class="search" id="search-<?=$SEARCH_ID++?>">
Many thanks to you both. I haven’t tested yet, but I expect you’ve given me exactly what I need. While the PHP.net references may have seemed to be obvious places for me to check, as only an occasional programmer whose brain is still crufty with rules from other languages (and with, obviously, an incomplete understanding of the differences between setting and declaring variables) your pointing them out was very helpful.