Dynamically Generate WordPress Shortcodes

后端 未结 2 1301
旧巷少年郎
旧巷少年郎 2021-01-15 11:51

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.

相关标签:
2条回答
  • 2021-01-15 12:33

    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);
        });
    }
    
    ?>
    
    0 讨论(0)
  • 2021-01-15 12:35

    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

    0 讨论(0)
提交回复
热议问题