如何传递可变的 wordpress 短代码 [英] How can I pass a variable wordpress shortcode

查看:23
本文介绍了如何传递可变的 wordpress 短代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个动态创建字符串的 Wordpress 插件.我想使用 wp_head 钩子将此字符串插入到元标记中.

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.

我的插件的工作原理如下:我定义了一个短代码,它的处理函数声明了一个 add_action(...,它在标题中添加了一个特殊的 标签.

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.

这行得通,但是...

我唯一的问题是我不知道如何传递包含字符串的变量以打印到头部.变量未定义,即使我在插件中将其全球化.

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
}

结果有效,除了 $head_string 变量为空.所以它打印一个空的元标记.(我知道其他一切都有效,因为我可以更改 add_meta_tags() 来执行类似 echo "FAKE META TAG"; 的操作,并且它会显示在标题中的位置.)

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.

推荐答案

尝试在函数中将 $head_string 设置为全局.

Try setting $head_string as global inside your functions.

这篇关于如何传递可变的 wordpress 短代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆