问题描述
在一个插件类中,我想为公共数据提供简单的字段:电子邮件,电话号码,Twitter 等。列表可以扩展。
有关详细信息,请参阅 GitHub 上的 plugin Public Contact Data 。
为了保持简单的使用,我也想提供一些易于输入的短码:
-
[public_email]
-
[public_phone]
-
[public_something]
唯一的区别是第二部分。我不想要更多的参数,因为它们是容易出错的。所以我为我的插件类中的所有字段注册一个短码处理程序:
foreach ( $this->fields as $key => $value )
{
add_shortcode( 'public_' . $key, array( $this, 'shortcode_handler' ) );
}
现在 shortcode_handler()
必须知道哪个短码被称为。我的问题是:我该怎么做?
我目前的解决方法是另一个功能:
protected function current_shortcode()
{
$backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS );
return $backtrace[3]['args'][0][2];
}
这… 适用于 the_content()
。但它既不优雅也不健壮。我已经读过 wp-includes/shortcodes.php
,但是我现在看不到如何做得更好。
最佳解决方案
这是未经测试的,但是回调函数提供了一个参数数组 $args
,它给出 (如果有的话) 提供 shortocode 的参数。第零个条目有时包含使用的短码的名称 (例如 public_email
) 。有时我的意思是
The zeroeth entry of the attributes array ($atts[0]) will contain the string that matched the shortcode regex, but ONLY if that differs from the callback name, which otherwise appears as the third argument to the callback function.
(见 Codex) 。为了您的目的,$atts[0]
将包含 public_email
,public_phone
等。
function shortcode_handler($atts,$content=NULL){
if(!isset($atts[0]))
return; //error?
switch($atts[0]):
case 'public_email':
//deal with this case
break;
case 'public_phone':
//deal with this case
break;
case 'public_something':
//deal with this case
break;
endswitch;
}
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。