• Resolved cncup

    (@cncup)


    The following php snippet features a const, global variable and a shortcode function:

    $some_var = 'one';
    
    const SOME_CONST = 'two';
    
    function shortcode_func() {
    	global $some_var;
    	return 'some_var=' . $some_var . ', SOME_CONST=' . SOME_CONST;
    }
    
    add_shortcode( 'shortcode_name', 'shortcode_func' );

    The snippet is set as php, Auto Insert, Run Everywhere.
    The shortcode function is called as per usual by placing [shortcode_name] inside the page markup.

    When the function is called, the output is:

    some_var=, SOME_CONST=two

    The const is recognized (showing that the snippet is executed as a whole, not just the function) but the global variable is not recognized. What gives?

    To note, the global variable in my actual code is set in a different snippet and the code is more involved, so I’m not looking for a workaround to bypass using the global variable in this particular example. I want to know how to get global variables to work in WPCode, in general.

    Thank you.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Mircea Sandu

    (@gripgrip)

    Hi @cncup,

    The variable you are defining in the first snippet has to be defined as global in the first snippet too and you also need to make sure the snippets are loaded in the correct order (you can use the Priority field to make sure of the order).

    Thread Starter cncup

    (@cncup)

    All that I did. The variable is defined as global in the first snippet. I played exhaustively with the Priority field. It changed nothing.

    Please note the example I gave here is of one snippet. The global variable doesn’t work even in the context of one snippet alone.

    Thread Starter cncup

    (@cncup)

    Oh I see now. The variable has to be defined as global also outside the function. Which was probably what you meant I suppose.

    So simply adding the global definition before the assignment:

    global $some_var;
    $some_var = 'one';
    
    function shortcode_func() {
    	global $some_var;
    	...
    }

    And it works.

    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to work with global php variables’ is closed to new replies.