I have in wordpress functions.php file
This sample works with one variable only, but i want multiple variables
function variables() {
$var1 = 'lorem';
return $var1;
}
in the front template results “lorem”:
echo variables();
works fine, but if i have many variables how can i displayed it?
example:
echo variables('var1');
echo variables('var2');
echo variables('etc');
i found a solution using global variables, but i don’t like use that.
edit:
in functions.php add variables :
$some = "lorem 1" $some2 = "lorem 2" $some3 = "lorem 3"
then display in theme
<?php echo some(); ?> <?php echo some2(); ?> <?php echo some3(); ?>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You have to think into the opposite direction: Don’t pull the variables from the template, push them into it. Templates should be as simple as possible, the shouldn’t know anything about the content of the rest of your code, for example function names.
In other words: use hooks.
In your template:
// the numbers are just context examples do_action( 'something', 'one' ); do_action( 'something', 'two' ); do_action( 'something', 'three' );
In your functions.php, you add a callback to that action:
// 1, 2, 3 are your variables
add_action( 'something', function( $context ) {
switch ( $context )
{
case 'one':
echo 1;
break;
case 'two':
echo 2;
break;
case 'three':
echo 3;
break;
default:
echo 'Context parameter is wrong!';
}
});
You can of course also echo more than one line and do some more complex stuff in the callback handler.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0