Site icon Hip-Hop Website Design and Development

How to set and use global variables? Or why not to use them at all

UPDATE: My original question has been solved, but this is turning into a valid discussion about why not to use global variables, so I am updating the question to reflect that. The solution was <?php global $category_link_prop; echo esc_url( $category_link_prop ); ?> as @TomJNowell suggested.

UPDATE 2: I now have it doing exactly what I wanted. But I’m still using global scope and would be happy to find a better way.

I am trying to set up a whole bunch of global variables for the permalinks to categories to be used in various places in my theme. The main reason for this is for use in both the main navigation, as well as in a series of sub navigations that are chosen based on what category the current post is in. This is not a theme I will be releasing for use by others, but is built for one very specific purpose.

This is how I am currently creating them (I’ve only pasted in a few of the variables).

function set_global_nav_var()
{
    //proposal
    global $prop;
    // Get the ID of a given category
    $category_id_prop = get_cat_ID( 'proposal' );
    // Get the URL of this category
    $category_link_prop = get_category_link( $category_id_prop );
    $prop = '<a href="' .esc_url( $category_link_prop ). '" title="Proposal">Proposal</a>';

    //Calvinball
    global $cb;
    // Get the ID of a given category
    $category_id_cb = get_cat_ID( 'calvinball' );
    // Get the URL of this category
    $category_link_cb = get_category_link( $category_id_cb );
    $cb = '<a href="' .esc_url( $category_link_cb). '" title="Calvinball">Calvinball</a>';
}
add_action( 'init', 'set_global_nav_var' );

I can now do <?php global $prop; echo $prop; ?> int he 4 places that goes and get back the whole link for the code. When that changes I only need to change it in one place. I’m open to alternatives that do not involve the global scope.