最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Autogenerate shortcodes from an array of strings

programmeradmin2浏览0评论

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 0
Add a comment  | 

1 Answer 1

Reset to default 3

Your 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;
    });
}
发布评论

评论列表(0)

  1. 暂无评论