确定Widget实例和边栏位置?

时间:2012-07-05 作者:Chuck

使用过滤器时:

add_filter(\'widget_display_callback\', \'function_name\');

function function_name($instance) {
   /* Some Code */
   return $instance;
}
是否可以确定特定小部件实例所在的侧栏名称和/或IDfunction_name?

1 个回复
SO网友:brasofilo

这个widget_display_callback hook接受3个参数,如中所示/wp-includes/widgets.php: (第180行,WP 3.4.2)

  • $instance = apply_filters(\'widget_display_callback\', $instance, $this, $args);

    // Priority = 10 // Arguments = 3
    add_filter(\'widget_display_callback\', \'wpse_57546_widget_display_callback\', 10, 3);
    
    // Using "$this" as an argument produces errors, 
    // as it is a reference to the current object
    // see http://stackoverflow.com/q/1523479/1287812
    // hence it is renamed to "$thiz"
    function wpse_57546_widget_display_callback( $instance, $thiz, $args ) 
    {
        /* Some Code */
        return $instance;
    }
    
    使用FirePHP, 我们看到这个过滤器在前端显示的所有小部件中运行,下面是小部件“类别”的值:

    $instance = array(
        [\'title\'] =>
        [\'count\'] => 0
        [\'hierarchical\'] => 0
        [\'dropdown\'] => 0
    )
    
    $thiz = WP_Widget_Categories(
        id_base = \'categories\'
        name = \'Categories\'
        widget_options = array(
            [\'classname\'] => \'widget_categories\'
            [\'description\'] => \'A list or dropdown of categories\'
        )
        control_options = array(
            [\'id_base\'] => \'categories\'
        )
        number = 2
        id = \'categories-2\'
        updated =
        option_name = \'widget_categories\'
    )
    
    $args = array(
        [\'name\'] => \'Main Sidebar\'
        [\'id\'] => \'sidebar-1\'
        [\'description\'] =>
        [\'class\'] =>
        [\'before_widget\'] => \'<aside id="categories-2" class="widget widget_categories">\'
        [\'after_widget\'] => \'</aside>\'
        [\'before_title\'] => \'<h3 class="widget-title">\'
        [\'after_title\'] => \'</h3>\'
        [\'widget_id\'] => \'categories-2\'
        [\'widget_name\'] => \'Categories\'
    )
    
    您要查找的值在$args:

    $args[\'id\']
    $args[\'widget_id\']
    
    和访问$thiz 值,您可以使用:

    $thiz->id_base
    $thiz->widget_options[\'classname\']
    

结束

相关推荐

Quote rotator in the sidebar

我喜欢在帖子编辑器中设计一些帖子(加粗和链接)(简单而有趣),并将其归类为“引用”。然后在侧边栏中基于CSS显示它,随机旋转它,如每5秒显示1。你知道一个插件可以做到这一点吗?