如何以正确的方式将属性添加到 Wordpress 短代码(OOP 样式)?
How to add attribute(s) to Wordpress shortcode (OOP style) in a proper way?
如何为 Wordpress 中的 class 添加适当的属性(在本例中为语言)以便在短代码中使用?
假设我们有 class 调用 FormHandler
class FormHandler {
private $language = 'en';
public function __construct($language = null) {
if ($language !== null) {
$this->language = $language;
}
}
public function display_form() {
if ($this->language === 'se' {
return 'return html for the swedish form';
}
else {
return 'return html for the english form';
}
}
}
add_shortcode( 'contactform', array('FormHandler', 'display_form') );
在 wordpress 中,我想在内容中添加短代码,例如
[contactform lang=en] or [contactform lang=en] based on the language.
我可以使用全局变量来获取实际的语言,但这似乎不是实现此目的的正确方法。
您需要在 display_form
函数中接受一个参数,以接收从短代码传入的属性。
public function display_form( $attrs )
{
// you should have your defaults here
$defaults = array(
'lang' => $this->language
);
$args = wp_parse_args( $attrs, $defaults );
// now extract so you can use the variable directly
extract( $args );
if ( $lang == 'se' )
{
$html = 'Swedish';
} else
{
$html = 'English';
}
return $html;
}
现在您可以使用短代码了 - 但不要忘记语言周围的引号:[contactform lang="se"]
如何为 Wordpress 中的 class 添加适当的属性(在本例中为语言)以便在短代码中使用?
假设我们有 class 调用 FormHandler
class FormHandler {
private $language = 'en';
public function __construct($language = null) {
if ($language !== null) {
$this->language = $language;
}
}
public function display_form() {
if ($this->language === 'se' {
return 'return html for the swedish form';
}
else {
return 'return html for the english form';
}
}
}
add_shortcode( 'contactform', array('FormHandler', 'display_form') );
在 wordpress 中,我想在内容中添加短代码,例如
[contactform lang=en] or [contactform lang=en] based on the language.
我可以使用全局变量来获取实际的语言,但这似乎不是实现此目的的正确方法。
您需要在 display_form
函数中接受一个参数,以接收从短代码传入的属性。
public function display_form( $attrs )
{
// you should have your defaults here
$defaults = array(
'lang' => $this->language
);
$args = wp_parse_args( $attrs, $defaults );
// now extract so you can use the variable directly
extract( $args );
if ( $lang == 'se' )
{
$html = 'Swedish';
} else
{
$html = 'English';
}
return $html;
}
现在您可以使用短代码了 - 但不要忘记语言周围的引号:[contactform lang="se"]