Autogenerate shortcodes from an array of strings

Question

I have to create a lot of shortcodes of the form

function foobar_sc( $atts ) {
    remove_filter( 'the_content', 'wpautop' );
    $content = apply_filters( 'the_content', '<div class=con>[block slug=foobar]</div>' );
    add_filter( 'the_content', 'wpautop' );
    return $content;
}
add_shortcode( 'foobar', 'foobar_sc' );

whose names are listed in an array

$shortcodes = array("foo", "bar", ...);

I tried with

$shortcodes = array("foo", "bar");
foreach ($shortcodes as $name) {
    add_shortcode( '$name', '$name_sc' );
    function $name_sc( $atts ) {
        remove_filter( 'the_content', 'wpautop' );
        $content = apply_filters( 'the_content', '<div class=con>[block slug=$name]</div>' );
        add_filter( 'the_content', 'wpautop' );
        return $content;
    }
}

but I get the error Fatal error: syntax error, unexpected ‘$name_sc’ (T_VARIABLE), expecting ‘(‘ on line function $name_sc( $atts ) {

Is it possible to solve it?

0
, sound wave 3 years 2019-10-28T17:06:06-05:00 0 Answers 94 views 0

Leave an answer

Browse
Browse