如何在Wordpress中使用选项创建短代码


How to create shortcodes with options in Wordpress

我有点想弄清楚如何为我正在构建的主题创建带有选项的简码。

简码创建一个容器,我想要一个"style"参数,以便用户可以输入如下内容:

[container style="white"]content[/container]

我有三种样式:白色,透明和彩色,每种样式应分别将类样式1,样式2和样式3添加到容器html中。这是我到目前为止在我的 php 中拥有的内容:

// Container
function container($atts, $content = null) {
   extract( shortcode_atts( array(
      'style' => 'style2',
     ), $atts ) );
    $return_string = '<section class="wrapper special container {$style}">'. do_shortcode($content) .'</section>';
    wp_reset_query();
   return $return_string;
}

我只是想通过让它注册 1 种风格来开始,但我什至还没有达到这一点,更不用说三种不同的风格了!

目前,这仅输出:

<section class="wrapper special container {$style}">[MY CONTENT]</section>

在 HTML 中 - 任何帮助或建议都会很棒。

> 1] 尝试在 $style 变量上使用开关,根据其值回显相应的$return_string

2] 特别注意default:情况,因为如果未设置为 clearwhite,将显示$style 。我将其设置为没有属性,但您可能希望它有所不同。

3] 您可以根据需要为短代码添加任意数量的案例。无论$style的值是多少,都将决定使用哪个$return_string

function container($atts, $content = null) {
   extract( shortcode_atts( array(
      'style' => '',
     ), $atts ) );
    switch ($style) {
        case "clear":
        $return_string = "<section class='"wrapper special container style1'">". do_shortcode($content) ."</section>"; // Adds style1 if clear
        break;
        case "white":
        $return_string = "<section class='"wrapper special container style2'">". do_shortcode($content) ."</section>"; // Adds style2 if white
        break;
        default:
        $return_string = "<section class='"wrapper special container'">". do_shortcode($content) ."</section>"; // No Attribute (default)
        break;
        }
   wp_reset_query();
   return $return_string;
}