Bonsoir,我想以数组的形式将shortcode属性和shorcode的名称传递给我的类,但在wordpress codex中没有说明我该怎么做,这是我的代码
$atributos=array(\'url\' => \' \',\'text\' => \' \');
$shortcode_name="myshortcode";
class MyLittleClass {
public static function exe_short( $atts, $atributos, $shortcode_name) {
$_atts = shortcode_atts($atributos, $atts );
// Attributes turn to variables
$url = $_atts[\'url\'];
$text = $_atts[\'text\'];
ob_start();
include(ABS_DIR . \'/includes/dynamics/\'.$shortcode_name.\'/index.php\');
$content = ob_get_clean();
return $content;
}
}
add_shortcode( $shortcode_name, array( \'MyPlugin\', \'exe_short\');
我知道我没有将变量$atributos和$shortcode\\u name作为函数add\\u shortcode()中exeshort()的参数传递,但如果我这样做
add_shortcode( $shortcode_name, array( \'MyPlugin\',exe_short($atts, $atributos, $shortcode_name))
它也不起作用,我如何将这些变量传递给我的类函数?
最合适的回答,由SO网友:mmm 整理而成
要创建多个短代码,可以从类的静态属性中获取默认值。此代码创建2个短代码myshortcode1
和myshortcode2
. 在包含的文件中,可以读取变量$_atts
, $content
和$tag
class MyLittleClass {
public static $shortcodes;
public static function init() {
self::$shortcodes = [
"myshortcode1" => [
"defaultValues" => [
"text" => "my link",
"url" => home_url("/"),
],
],
"myshortcode2" => [
"defaultValues" => [
"color" => "#EEC",
],
],
];
foreach (array_keys(self::$shortcodes) as $code) {
add_shortcode($code, [__CLASS__, "exe_short"]);
}
}
public static function exe_short($attr, $content, $tag) {
$atributos = self::$shortcodes[$tag]["defaultValues"];
$_atts = shortcode_atts($atributos, $attr, $tag);
ob_start();
include(ABS_DIR . \'/includes/dynamics/\'.$tag.\'/index.php\');
$content = ob_get_clean();
return $content;
}
}
MyLittleClass::init();
您还可以在以下位置传递数组时创建短代码:
init
或在初始化时创建筛选器
$shortcodes
.
SO网友:mmm
如果无法修改该方法exe_short
, 您可以创建这样的新方法
class MyLittleClass {
public static function exe_short2($attr, $content, $tag) {
$atts = $attr;
$atributos = ["url" => "", "text" => $content];
$shortcode_name = $tag;
return self::exe_short( $atts, $atributos, $shortcode_name);
}
public static function exe_short( $atts, $atributos, $shortcode_name) {
$_atts = shortcode_atts($atributos, $atts );
// Attributes turn to variables
$url = $_atts[\'url\'];
$text = $_atts[\'text\'];
ob_start();
include(ABS_DIR . \'/includes/dynamics/\'.$shortcode_name.\'/index.php\');
$content = ob_get_clean();
return $content;
}
}
add_shortcode( "myshortcode", array( \'MyPlugin\', \'exe_short2\');