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?
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?
Share Improve this question asked Oct 28, 2019 at 22:06 sound wavesound wave 2151 gold badge3 silver badges15 bronze badges 01 Answer
Reset to default 3Your shortcode name ('$name' ) is invalid. If you want to use the variable, it should be add_shorcode( $name, ...
. Also, the function name is invalid. Since you want to make it "dynamic" (I'm assuming you want it to be {$name}_sc, then maybe you should use an anonymous function.
What you have is somewhat unconventional (IMO), so I don't know if this will work, but try this:
$shortcodes = array("foo", "bar");
foreach ($shortcodes as $name) {
add_shortcode( $name, function ( $atts ) use ( $name ) {
remove_filter( 'the_content', 'wpautop' );
$content = apply_filters( 'the_content', '<div class=con>[block slug=' . $name . ']</div>' );
add_filter( 'the_content', 'wpautop' );
return $content;
});
}