【问题标题】:Detecting parameter names in php function for wordpress shortcode?在 php 函数中检测 wordpress 简码的参数名称?
【发布时间】:2013-08-19 14:05:22
【问题描述】:

我试图让你理解这个函数,作为分叉它为我自己的短代码创建类似函数的序言。我了解如何定义简码及其功能。我也基本上“了解”了原作者在这里所做的事情:从短代码中收集参数并将它们组装成 HTML 标签并返回该标签。似乎参数的顺序并不重要,但它们的名称是。

但是,当我使用此代码时,它似乎不明白哪个参数是哪个。例如,原始文档说要像这样使用简码: [button link="http://google.com" color="black" size="small"]Button Text[/button]

但是当我使用这个简码时,我得到:

<a href="Button Text" title="Array" class="button button-small button " target="_self">
  <span>Array</span>
</a>

这是我的 PHP:

if( ! function_exists( 'make_button' ) ) {
function make_button( $text, $url, $color = 'default', $target = '_self', $size = 'small', $classes = null, $title = null ) {
    if( $target == 'lightbox' ) {
        $lightbox = ' rel="lightbox"';
        $target = null;
    } else {
        $lightbox = null;
        $target = ' target="'.$target.'"';
    }
    if( ! $title )
        $title = $text;
    $output = '<a href="'.$url.'" title="'.$title.'" class="button button-'.$size.' '.$color.' '.$classes.'"'.$target.$lightbox.'>';
    $output .= '<span>'.$text.'</span>';
    $output .= '</a>';
    return $output;
}
}


add_shortcode( 'button', 'make_button' );

【问题讨论】:

    标签: php wordpress shortcode


    【解决方案1】:

    查看Shortcode API的文档,其中明确指出将三个参数传递给短代码回调函数:

    • $atts - 属性的关联数组,如果没有,则为空字符串 给定属性
    • $content - 封闭的内容(如果短代码以其封闭形式使用)
    • $tag - 简码标签,用于共享回调函数

    所以函数定义应该是这样的:

    function make_button( $atts, $content, $tag ) {
        // use print_r to examine attributes
        print_r($atts);
    }
    

    【讨论】:

      【解决方案2】:

      短代码明确寻找$text

      [button url="http://google.com" color="black" size="small" text="Button Text"]
      

      根据Shortcode API,使用打开/关闭短代码时设置的变量通常是$content。另一个解决方法是更改​​简码以查找 $content 而不是 $text

      【讨论】:

      • 我在发帖之前试过了,还是得到了上面贴的按钮。
      • 所有参数都存储在变量$atts中,你可以var_dump这个变量,看看属性是如何存储在短代码中的?
      • 是的,我完全不明白原作者是如何做到这一点的。我最后把它撕掉并使用上述方法构造标签,如$atts['link']
      猜你喜欢
      • 2011-11-25
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      相关资源
      最近更新 更多