Support

Account

Home Forums General Issues Is there a way to store shared variables in one place to reuse?

Solving

Is there a way to store shared variables in one place to reuse?

  • I have a theme that is setup using multiple flex-layouts that share a common set of options. I have the options defined as clone fields so they can be managed from one place but in the template files I need to re-declare the these same options in multiple files for the different flex-layouts.

    Is there anyway I can have the variables declarations for all of these fields stored in one file that I can pull for each time I need it? Right now I just have the same variables from my clone field copy and pasted in every flex-layout file that use them.

    I tried storing them in a separate file and pulling them with get_template_part but none of the variables defined in that template part file were able to be read.

    Let me know if anyone has any ideas or needs more information to advise. Thank you!

  • I’m thinking storing the variables as an array in a PHP constant or WP transient (https://developer.wordpress.org/reference/functions/set_transient/).

  • This has to do with variable scope. When you use get_template_part() your template is included inside of a function and only variables declared inside of that function are available to your template file.

    Besides the above you could use global variables.

    Another way would be do include your template using a php include instead and bypassing WP. Doing this any variables that are available in the calling template plus any variables you create in your calling template are available in your included file. Like everything, this has it’s ups and downs.

    Another possibility it to “include” the file that defines the common variables in each of your templates that are called using get_template_part() thus making them available to the calling file.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.