I want an element to appear within the Loop, but only at certain points. I can supply the condition - in the form of a "flag" that gets set when the condition is fulfilled, preventing further iteration - directly in a template file, and it works, but when I produce the identical logic via function the flag does not seem to be set.
In other words - providing a simplified (the simplest!) case - the following works - CASE 1:
while( have_posts() ) : the_post();
if ( $flag < 1 ) {
echo 'Flag worked!';
$flag = 1;
}
/* all of the code producing a post */
endwhile;
The above works as expected: "Flag worked!" appears once and never again.
If, however - CASE 2 - I write a function, like so, and add it to the theme functions.php...
function flag_it() {
if ( $flag < 1 ) {
echo 'Flag worked!';
$flag = 1;
}
}
...and then place it in the exact same place as the first code, like so:
while( have_posts() ) : the_post();
flag_it();
/* all of the code producing a post */
endwhile;
The words "Flag worked" are turned into a lie, and appear before every post in the loop. In other words, the $flag value is not assessed by the if conditional, or the value of $flag continues to be treated as NULL ( so, "$flag < 1" remains true).
I've tried variations on the theme - with TRUE v FALSE, returned variables, value declared as 0, etc. - but none works, or, if it did!, would answer the basic question: Why does case 1 work, but not case 2, and is there any way to make case 2 or something like it - flagged condition supplied via function - work?