我必须创建许多表单的短代码
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\' );
其名称列在数组中
$shortcodes = array("foo", "bar", ...);
我试过了
$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;
}
}
但我发现了错误
Fatal error: syntax error, unexpected \'$name_sc\' (T_VARIABLE), expecting \'(\' on line function $name_sc( $atts ) {有可能解决吗?
最合适的回答,由SO网友:butlerblog 整理而成
您的短代码名称(“$名称”)无效。如果要使用该变量,则应为add_shorcode( $name, ...
. 此外,函数名无效。既然您想让它“动态”(我假设您希望它是{$name}\\u sc,那么也许您应该使用匿名函数。
你所拥有的有些非传统(IMO),所以我不知道这是否可行,但试试这个:
$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;
});
}