在第一个实例后切换并中止在下面的示例中,您可以找到static
未在第一个实例上设置的变量。如果小部件第一次被调用,我们将其设置为true。在第二次运行时,我们中止运行return
没有实际为用户提供任何服务。
class My_Widget extends WP_Widget {
// You static instance switch
static $instance;
function My_Widget() {
// We set the static class var to true on the first run
if ( ! $this->instance ) {
$this->instance = true;
}
// abort silently for the second instance of the widget
else {
return;
}
// widget actual processes
}
function form($instance) {
// outputs the options form on admin
}
function update($new_instance, $old_instance) {
// processes widget options to be saved
}
function widget($args, $instance) {
// outputs the content of the widget
}
}
register_widget(\'My_Widget\');
代码取自相关
Widgets API Codex article处理全局小部件数组的另一个选项可能是检查包含所有已注册小部件的全局数组:
function wpse32103_show_widgets()
{
$dump = \'<pre>\';
$dump .= var_export( $GLOBALS[\'wp_registered_widgets\'], false );
$dump .= \'</pre>\';
return print $dump;
}
add_action( \'shutdown\', \'wpse32103_show_widgets\' );
关联数组的输出包含名称作为键,后面附加
-2
(数量增加)。您可以在
init
或
admin_init
如果您找到了第二个实例,则挂起并简单地取消设置。可能如下所示:
function wpse32103_show_widgets()
{
global $wp_registered_widgets;
// Go and search for your widgets name with the above written function
$target = \'FILL IN YOUR FOUND ARRAY KEY HERE. Without -2 (or any other appending number)\';
// Container for your targeted widget(s)
$unsets = array();
foreach ( array_keys( $wp_registered_widgets ) as $widget )
{
// remove dashes
$widget_check = str_replace( \'-\', \'\', $widget );
// remove numbers
$widget_check = preg_replace( \'/[^0-9]/\', \'\', $widget );
// if we match, do it in our container
if ( $widget_check === $target )
$unsets[] = $widget;
}
// less than one element in the container: abort
if ( ! count ( $unsets ) > 1 )
return;
// preserve first element
array_shift( array_values( $unsets ) );
// unset all left instances from the global array
foreach ( $unsets as $unset )
unset ( $wp_registered_widgets[ $unset ] );
return;
}
add_action( \'init\', \'wpse32103_show_widgets\' );