【问题标题】:How to create shortcodes with options in Wordpress如何在 Wordpress 中使用选项创建简码
【发布时间】:2014-04-25 08:20:29
【问题描述】:

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

短代码创建一个容器,我想要一个“样式”参数,以便用户可以输入如下内容:

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

我有三种样式:白色、透明和彩色,每种样式都应分别将类 style1、style2 和 style 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 中 - 任何帮助或建议都会很棒。

【问题讨论】:

标签: php wordpress shortcode


【解决方案1】:

1]尝试使用$style 变量上的开关来回显对应的$return_string,具体取决于它的值。

2] 请特别注意default: 的大小写,因为如果$style 未设置为clearwhite,则会显示该大小写。我将它设置为没有属性,但您可能希望它有所不同。

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;
}

【讨论】:

  • 这让我更接近了,目前用户必须在简码中写 'style1'、'style2' 等,而我希望他们写 'clear' 并且简码填写 'style1' 或 ' white' 和短代码填写 'style2' 等
  • 得到以下错误:语法错误,意外':'指的是带有“case:”clear”的行:就可以了
猜你喜欢
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 2023-01-11
  • 2012-11-10
  • 1970-01-01
  • 2017-05-17
相关资源
最近更新 更多