我发现为自定义小部件添加类的另一种方法是使用\'classname\' 构造函数的键,如:
class My_Widget_Class extends WP_Widget {
// Prior PHP5 use the children class name for the constructor…
// function My_Widget_Class()
function __construct() {
$widget_ops = array(
\'classname\' => \'my-class-name\',
\'description\' => __("Widget for the sake of Mankind",\'themedomain\'),
);
$control_ops = array(
\'id_base\' => \'my-widget-class-widget\'
);
//some more code after...
// Call parent constructor you may substitute the 1st argument by $control_ops[\'id_base\'] and remove the 4th.
parent::__construct(@func_get_arg(0),@func_get_arg(1),$widget_ops,$control_ops);
}
}
并确保使用默认值\'
before_widget\' 在您的主题中或如果您使用
register_sidebar()
在功能中。php,这样做:
//This is just an example.
register_sidebar(array(
\'name\'=> \'Sidebar\',
\'id\' => \'sidebar-default\',
\'class\' => \'\',//I never found where this is used...
\'description\' => \'A sidebar for Mankind\',
\'before_widget\' => \'<aside id="%1$s" class="widget %2$s">\',//This is the important code!!
\'after_widget\' => \'</aside>\',
\'before_title\' => \'<h3>\',
\'after_title\' => \'</h3>\',
));
然后,在您的小部件的每个实例上,都会有这样的类“小部件我的类名”:
<aside class="widget my-class-name" id="my-widget-class-widget-N"><!-- where N is a number -->
<h3>WIDGET TITLE</h3>
<p>WIDGET CONTENT</p>
</aside>
您也可以先调用父构造函数,然后附加所需的任何类名:
class My_Widget_Class extends WP_Widget {
// Better defining the parent argument list …
function __construct($id_base, $name, $widget_options = array(), $control_options = array())
{ parent::__construct($id_base, $name, $widget_options, $control_options);
// Change the class name after
$this->widget_options[\'classname\'].= \' some-extra\';
}
}