我正在努力理解这个函数,作为分叉它为我自己的短代码生成类似函数的序言。我了解如何定义快捷代码及其功能。我还基本上"了解"了原作者在这里所做的事情:从短代码中收集参数,并将它们组装成一个HTML标记,然后返回该标记。看起来params的顺序并不重要,但他们的名字是。
然而,当我使用这段代码时,它似乎不明白哪个参数是哪个。例如,原始文档说要使用这样的短代码:[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' );
请参阅Shortcode API的文档,其中明确说明了将三个参数传递给Shortcode回调函数:
- $atts-属性的关联数组,如果没有,则为空字符串给定了属性
- $content-封闭的内容(如果以封闭形式使用快捷代码)
- $tag-shortcode标记,用于共享回调函数
因此,函数定义应该看起来像:
function make_button( $atts, $content, $tag ) {
// use print_r to examine attributes
print_r($atts);
}
短代码显式查找$text
。
[button url="http://google.com" color="black" size="small" text="Button Text"]
通常,根据shortcode API,使用打开/关闭快捷代码时设置的变量为$content
。另一个修复方法是更改短代码以查找$content
而不是$text
。