我发现为自定义窗口小部件添加类的另一种方法是使用构造函数的“ 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()
在function.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>',
));
然后,在小部件的每个实例上,您都将具有以下类“ widget my-class-name”:
<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';
}
}