WordPress 中的动态短代码和功能 [英] Dynamic shortcodes and functions in WordPress

查看:38
本文介绍了WordPress 中的动态短代码和功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在根据数据库条目自动生成短代码时遇到了一些问题.

I am having a bit of an issue with autogenerating shortcodes, based on database entries.

我能够得到一个正常的短代码,即:

I am able to get a normal shortcode working i.e:

function route_sc5() {
        return "<div>Route 5</div>";
    }
    add_shortcode('route 5','route_sc');

和以下激活它的短代码是 [route 5]

and the following shortcode to activate it would be [route 5]

这有效.但我需要的是为每个数据库条目生成的简码.类似:

This works. But what I need is the shortcode to be produced for each database entry. something like:

$routes = $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_routes") );
foreach($routes as $route)
{
    function route_sc$route->id () {
        return "<div>Route $route->id</div>";
    }
    add_shortcode('route $route->id','route_sc$route->id');
}

以上只是我希望它如何工作的一个例子.不是我正在使用的代码.我将如何实现这一目标?):谢谢.

The above is just an example of how I want it to work. Not literally the code I am using. How would I go about achieving this? ): Thanks.

推荐答案

以下是使用 PHP 5.3 的动态短代码回调示例 匿名函数:

Here's an example of dynamic shortcode callbacks using PHP 5.3 anonymous functions:

for( $i = 1; $i <= 5; $i++ ) { 
    $cb = function() use ($i) {
        return "<div>Route $i</div>";
    };  

    add_shortcode( "route $i", $cb );
}

不过,我不得不问:你能用短代码参数完成你需要做的事情吗?IE.[路线编号=3].那么你可以只拥有一个 handle_route() 函数和一个 [route] 短代码,这可以简化事情.

I have to ask, though: can you just accomplish what you need to do using shortcode arguments? ie. [route num=3]. Then you could just have one handle_route() function and one [route] shortcode, which may simplify things.

此外,虽然从技术上讲,您可以在名称中包含带有空格的短代码,但我认为这会造成混淆.如果您决定需要为每条路线指定特定的短代码,我会推荐route5"或route-5"而不是route 5".

Also, while technically you can include a shortcode with a space in the name, I think it creates a confusing ambiguity. If you decide you need specific shortcodes for each route, I would recommend "route5" or "route-5" rather than "route 5."

这篇关于WordPress 中的动态短代码和功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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