动态生成 W​​ordPress 简码 [英] Dynamically Generate WordPress Shortcodes

查看:15
本文介绍了动态生成 W​​ordPress 简码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更有效的方法来写这个,使用 while 循环或其他东西.本质上,我想动态生成一些 WordPress 短代码.

I'm wondering if there is a more efficient way to write this, using a while loop or something. Essentially, I want to dynamically generate a number of WordPress shortcodes.

# Span 1
add_shortcode('span-1', 'span1');
function span1($atts, $content = null) {
    return generateSpan(1, $content);
}

# Span 2
add_shortcode('span-2', 'span2');
function span2($atts, $content = null) {
    return generateSpan(2, $content);
}

// ... repeating as many times as necessary

我试过了,但似乎没有用:

I tried this, but it didn't seem to work:

$i = 1;
while ($i < 12) {

    $functionName = 'span' . $i;
    $shortcodeName = 'span-' . $i;

    add_shortcode($shortcodeName, $functionName);
    $$functionName = function($atts, $content = null) {
        return generateSpan($i, $content);
    };

    $i++;

}

推荐答案

我知道它不能解决动态生成"问题,但是,您也可以使用以下属性:[span cols="1"] -> [span cols="12"].

I know it doesn't answers the "dynamically generate" issue, but, alternatively, you could use the attributes for that: [span cols="1"] -> [span cols="12"].

add_shortcode('span', 'span_shortcode');

function span_shortcode( $atts, $content = null ) 
{
    if( isset( $atts['cols'] ) )
    {
       return generateSpan( $atts['cols'], $content );
    }  
}

并且回调的第三个参数可以用来检测当前的简码:

And the third parameter of the callback can be used to detect the current shortcode:

for( $i=1; $i<13; $i++ )
    add_shortcode( "span-$i", 'span_so_17473011' );

function span_so_17473011( $atts, $content = null, $shortcode ) 
{
    $current = str_replace( 'span-', '', $shortcode ); // Will get $i value
    return generateSpan( $current, $content );
}

参考: current_shortcode() - 检测当前使用的简码

这篇关于动态生成 W​​ordPress 简码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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