Dynamically Generate WordPress Shortcodes

2019-02-19 10:50发布

问题:

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++;

}

回答1:

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 );
}

Reference: current_shortcode() - detect currently used shortcode



回答2:

You should be able to do this:

<?php

$scName = 'span-';

for($i = 0; $i < 12; $i++)
{
    add_shortcode($scName . $i, function($atts, $content = null){
        return generateSpan($i, $content);
    });
}

?>


标签: php wordpress