In the example below, $shortcodes
is a multidimensional array with shortcode data.
foreach( $shortcodes as $shortcode ) {
// Here we have the shortcode name, could be 'custom_person_john'.
$shortcode_name = $shortcode['slug'];
// Anonymous function should be referred to as 'custom_person_john'.
$shortcode_name = function( $shortcode ) {
// Build shortcode attributes.
$atts = shortcode_atts( array(
'name' => 'john',
'type' => 'mammal'
), $atts );
$markup = '<div class="'.$atts['name'].'">';
$markup .= '<div>';
// $shortcode should contain custom markup from the array.
$markup .= $shortcode['html'];
$markup .= '</div>';
$markup .= '</div>';
return $markup;
};
// Trying to register the shortcode
add_shortcode( $shortcode['slug'], $shortcode_name( $shortcode ) );
};
So this is not working, but I can’t grasps why. If I dump all the registered shortcodes, they don’t show up in the list. Trying to load them simple echo’s [custom_person_john]. I don’t have errors either.
Edit: If anyone has other ideas on how to create them dynamically out of an array, feel free to suggest 🙂
the shortcodes doesn’t shop up in the liste because it’s not a valid declaration with a valid function callback on the 2nd argument
try this to see what append :
// shortcode data
add_filter("shortcode_list", function ($shortcode_list) {
$shortcode_list["slugA"] = array(
"html" => "test html 1",
);
return $shortcode_list;
});
add_filter("shortcode_list", function ($shortcode_list) {
$shortcode_list["slugB"] = array(
"html" => "test <strong>html 2 - [slugA]</strong>",
);
return $shortcode_list;
});
// shortcodes declaration
add_action("init", function () {
$shortcodes = apply_filters("shortcode_list", array());
foreach (array_keys($shortcodes) as $shortcode_slug) {
add_shortcode($shortcode_slug, "shortcode_callback");
};
});
// callback function
function shortcode_callback($atts, $content = "", $tag) {
// Build shortcode attributes.
$atts = shortcode_atts( array(
'name' => 'john',
'type' => 'mammal'
), $atts);
// shortcode data
$shortcodes = apply_filters("shortcode_list", array());
$shortcode = $shortcodes[$tag];
// construct result of the shortcode
$markup = "";
$markup .= '<div class="'.$atts['name'].'">';
$markup .= '<div>';
// $shortcode should contain custom markup from the array.
$markup .= $shortcode['html'];
//$markup .= do_shortcode($shortcode['html']); // to replace shortcodes in the "html" data
$markup .= '<pre>';
$markup .= print_r($atts, TRUE);
$markup .= '</pre>';
$markup .= '</div>';
$markup .= '</div>';
return $markup;
}