• Resolved aggk

    (@aggk)


    Hi,

    I’m building a custom shop (without any commerce plugin) that involves product customization where I calculate prices on the fly based of pricelists which I store in arrays…5 different arrays with arround 30 items/prices in each array.

    Now I need these same arrays in different templates and files and would prefer to keep these available in one place so that I can access the same prices from different files and templates, my first plan was to simply store the pricelists arrays inside template parts so that I could simply include the same template part into different places but from what I understand variables will not work like that.

    Grateful for any help on how to best store arrays central so that they are available in multiple places

    Thanks!

    • This topic was modified 2 years, 2 months ago by Jan Dembowski. Reason: Moved to Fixing WordPress, this is not an Developing with WordPress topic
Viewing 3 replies - 1 through 3 (of 3 total)
  • If it was me doing it that way I’d set up a function that returned the array as needed. That can be set up in a new plugin if you wanted to, or added to your themes (or child theme preferably) functions.php file.

    As a very quick example, something like…

    function get_variations ($product_id) {
        switch ($product_id) {
            case 1:
                $variations = array (1, 2, 3, 4, 5);
                break;
            case 2:
                $variations = array (5, 6, 7, 8, 9);
                break;
            case 3:
                $variations = array (2, 4, 6, 8, 10);
                break;
            default:
                $variations = array ();
        }
    
        return $variations;
    }

    That will keep things in one place, and you can update it easily (as long as you have access to edit that file).

    Dion

    (@diondesigns)

    Another option is to create a class with static variables, such as:

    final class pricelist {
    	private function __construct() {}
    
    	public static $one = [1,2,3,4,5];
    	public static $two = [2,4,6,8,10];
    	public static $three = [3,6,9,12,15];
    	public static $four = [4,8,12,16,20];
    	public static $five = [5,10,15,20,25];
    }

    You can now access the arrays statically from any file/function/etc. For example:

    pricelist::$one or pricelist::$four

    I added extra code to protect the class from being instantiated or extended; it can be removed if this is for your personal site. If you add this class to a theme/plugin file that has a namespace defined, you’ll need to access the arrays accordingly.

    Thread Starter aggk

    (@aggk)

    Thank you catacaustic and Dion!

    Those are both excellent ways to achieve exactly what I asked for.

    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘List of variables’ is closed to new replies.