2

while ループなどを使用して、これをより効率的に記述する方法があるかどうか疑問に思っています。基本的に、多数の WordPress ショートコードを動的に生成したいと考えています。

# 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 = 1;
while ($i < 12) {

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

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

    $i++;

}
4

2 に答える 2

2

「動的に生成する」問題に答えないことは知っていますが、代わりに、そのために属性を使用することもできます: [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 );
    }  
}

コールバックの 3 番目のパラメーターを使用して、現在のショートコードを検出できます。

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() - 現在使用されているショートコードを検出する

于 2013-07-04T15:54:49.180 に答える