0
votes

I have a custom timber function total_value in my twig.php file and in the Twig class.

class Twig {
public $totalvalue = 1;
public function add_timber_functions( $twig ) {
    /* actions and filters */
    $twig->addFunction(new Twig_Function('total_value', function ($value) {
        $this->totalvalue += $value;
        return ($this->totalvalue);
    }));
}
}

I also have a public variable in the Twig class public $totalvalue = 1;

If I call the function from one twig template like so {{ total_value('1') }}, it returns 2, as it should. But when I call it from another twig template after that it still returns 2, but I would like it to return 3.

Im very new to twig and timber and i cant really wrap my head around it

1
Is this in the same request or not? - DarkBee
@DarkBee Different requests I guess. Okay, now I see why my attempt did not work, cause the Twig class is getting reinitialized and that resets the $totalvalue variable? - SigsDuks
Yes, u'd need to store the variable in persistent storage like $_SESSION - DarkBee

1 Answers

0
votes

I would suggest you main options to be wp cache or transients. Thed ifference between transients and the cache is that transients are persistent and write to the options table, while the cache only persists for the particular page load.

As mentioned in the comments, $_SESSION is another way to store information to be used across multiple pages, although this is not persistent between different user sessions. Therefore depending on the functionatily required, you'll need to select accordingly. 

WP Cache

$value = wp_cache_get( 'hello' );
wp_cache_set( 'hello', 'world' );

Transient:

set_transient( 'box_color', 'Cherry Red', 14400 );
$value = get_transient( 'box_color' );

Timber also has a helper methd for transients, see documenation.