1

I'm using a plugin that allows you to set a global currency. However, I need to change the currency based on the page.

Is there any way to override a global variable on specific pages?

The variable I need to change is $currency. Here is what I've tried thus far based on what I've read here, but I'm not very familiar with PHP so I'm not sure how close I am to a solution.

function change_currency() {
global $currency;  
if( is_page ( 18 ) ) {
 $currency = "EUR";
}}

Thank you in advance.

Community
  • 1
  • 1
  • Are you using wordpress that you've used `is_page` function or You have defined it? – SAM Oct 01 '16 at 08:32
  • Yes, I'm using Wordpress. The page id in this case is 18. – Brian Kidwell Oct 01 '16 at 08:35
  • So your code is fine The variable is global and function is fine But I recommend use `$currency` in your function's argument To be functional! – SAM Oct 01 '16 at 08:38

2 Answers2

0

If you need to make $currency variable be global on the whole page then <?php global $currency; ?> is declare on the top of the page. Otherwise if you need inside a single function then use this function:

change_currency() 
{
    global $currency; 
}
SAM
  • 281
  • 3
  • 15
0

You could possible do something like this using the use keyword to import the variable to your method and return its new value.

function changeCurrency() use ($currency)
{
    .....
    return $currency;
}

$currency = changeCurrency();

Although this is Procedural oriented. My better solution would be to suggest that you create an object for what item your holding and the method for changing that currency through the object:

class Item
{
    private $currency;
    public function changeCurrency(
    ) {
         .....
         $this->currency = ....
Jaquarh
  • 6,493
  • 7
  • 34
  • 86