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++;
}
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"]
.And the third parameter of the callback can be used to detect the current shortcode:
Reference: current_shortcode() – detect currently used shortcode
You should be able to do this: