Dynamically Generate WordPress Shortcodes

后端 未结 2 1300
旧巷少年郎
旧巷少年郎 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: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

提交回复
热议问题