How can I pass a variable wordpress shortcode

2019-08-16 23:25发布

问题:

I'm writing a Wordpress plugin which dynamically creates a string. I want to insert this string in a meta tag using the wp_head hook.

My plugin works as follows: I define a shortcode whose handler function declares an add_action(... that adds a special <meta> tag into the header.

This works, BUT...

My only problem is that I can't figure out how to pass the variable containing the string to get printed into the head. The variable isn't defined, even though I globalize it in my plugin.

//INSIDE MY PLUGIN...

global $head_string;

function initialize_my_plugin_class() {
    $head_string = "<meta>bla bla bla</meta>";
}

function add_action('wp_head', 'add_meta_tags' ) //this is slightly oversimplified
                                                 //the execution order of wp_head makes
                                                 //the real code a bit more complicated
                                                 //for the purposes of this question let's
                                                 //pretend it's like this.

function add_meta_tags() {
    echo $head_string
}

The result works, EXCEPT that the $head_string variable is empty. So it prints an empty meta tag. (I know everything else works because I can change add_meta_tags() to do something like echo "FAKE META TAG"; and it shows up where it should in the header.)

So what's wrong with what I'm doing? I think it must involve variable scope, but I'm stuck.

回答1:

Try setting $head_string as global inside your functions.