0

I am working on a WordPress website. I was wondering how can I share some PHP variables which are needed in multiple different files without the need to copy-paste the same variables over and over again.

I have some taxonomy variables which I need to use in different files.

This is from my single.php file:

$taxonomy_themes    = wp_get_post_terms(get_the_ID(), 'themas');
$taxonomy_rubrieken = wp_get_post_terms(get_the_ID(), 'rubrieken');

$taxonomy_themes_singular_name    = $taxonomy_themes[0]->name;
$taxonomy_rubrieken_singular_name = $taxonomy_rubrieken[0]->name;
    
$taxonomy_themes_singular_slug    =  $taxonomy_themes[0]->slug;
$taxonomy_rubrieken_singular_slug =  $taxonomy_rubrieken[0]->slug;
    
$taxonomy_themes_singular_link    = get_term_link($taxonomy_themes_singular_slug, 'themas');
$taxonomy_rubrieken_singular_link = get_term_link($taxonomy_rubrieken_singular_slug, 'rubrieken');

How can I share these files globally with other files and use them?

  • 3
    Put them in their own file, and then include that file in your other scripts when you need it. See https://www.php.net/manual/en/function.include.php – ADyson Oct 30 '20 at 09:49
  • Does this answer your question? [How to access a variable across two files](https://stackoverflow.com/questions/18588972/how-to-access-a-variable-across-two-files) – Don't Panic Oct 30 '20 at 10:16

1 Answers1

-1

you can define them as a global variable using the php $GLOBALS method, the documentation of the function is available here

While it is possible to define resource constants, it is not recommended and may cause unpredictable behavior.

For you code

$taxonomy_themes    = wp_get_post_terms(get_the_ID(), 'themas');
$taxonomy_rubrieken = wp_get_post_terms(get_the_ID(), 'rubrieken');

$taxonomy_themes_singular_name    = $taxonomy_themes[0]->name;
$taxonomy_rubrieken_singular_name = $taxonomy_rubrieken[0]->name;
    
$taxonomy_themes_singular_slug    =  $taxonomy_themes[0]->slug;
$taxonomy_rubrieken_singular_slug =  $taxonomy_rubrieken[0]->slug;
    
$taxonomy_themes_singular_link    = get_term_link($taxonomy_themes_singular_slug, 'themas');
$taxonomy_rubrieken_singular_link = get_term_link($taxonomy_rubrieken_singular_slug, 'rubrieken');

 $GLOBALS['taxonomy_rubrieken_singular_link'] =  $taxonomy_rubrieken_singular_link;

// use the variable => without the dollar sign taxonomy_rubrieken_singular_link
var_dump($GLOBALS['taxonomy_rubrieken_singular_link']);
GABY KARAM
  • 359
  • 1
  • 8
  • I get: Constants may only evaluate to scalar values, arrays or resources –  Oct 30 '20 at 10:19
  • try to use $GLOBAL, if it didn't work than I recommend to create a class and define thus variables as static properties inside the constructor of the class – GABY KARAM Oct 30 '20 at 20:38