简体   繁体   English

如何传递可变的wordpress简码

[英]How can I pass a variable wordpress shortcode

I'm writing a Wordpress plugin which dynamically creates a string. 我正在写一个动态创建字符串的Wordpress插件。 I want to insert this string in a meta tag using the wp_head hook. 我想使用wp_head钩子将此字符串插入meta标签。

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. 我的插件的工作方式如下:我定义了一个短代码,其处理函数声明了一个add_action(... ,它将一个特殊的<meta>标记添加到标题中。

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. 结果有效,但$head_string变量为空。 So it prints an empty meta tag. 因此,它会打印一个空的meta标签。 (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.) (我知道其他所有方法都可以正常工作,因为我可以更改add_meta_tags()来执行类似echo "FAKE META TAG";它会在标头中显示该位置。)

So what's wrong with what I'm doing? 那么我在做什么呢? I think it must involve variable scope, but I'm stuck. 我认为它必须涉及可变范围,但是我被卡住了。

尝试将$ head_string设置为函数内部的全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM