从自定义小部件内将类添加到Being_Widget

时间:2011-06-01 作者:dashaluna

我有一个简单的自定义小部件,它要求它的宽度(稍后将在前端使用)。“宽度”字段是“选择”下拉列表,因此用户有预定义的选项。

我将有许多小部件的实例,每个都有自己的宽度设置。

现在,在我的小部件代码中,我有以下代码:

echo $before_widget;
其结果是:

<div class="widget my" id="my-widget-1"></div>
我想做的是$before_widget 并添加我自己的类(选择下拉列表中指定的宽度)。因此,我需要以下标记:

<div class="widget my col480" id="my-widget-3"></div>
如果没有指定类,那么我想添加class="col480".

我如何做到这一点?

谢谢你的帮助!达莎

5 个回复
最合适的回答,由SO网友:dashaluna 整理而成

啊哈,那么$before_widget 变量是表示div元素的字符串:<div class="widget my" id="my-widget-1"> . 所以我检查了$before_widget 为“class”子字符串添加$widget_width 它的价值。

代码来自我的自定义小部件文件:

function widget( $args, $instance ) {
  extract( $args );
  ... //other code

  $widget_width = !empty($instance[\'widget_width\']) ? $instance[\'widget_width\'] : "col300";
  /* Add the width from $widget_width to the class from the $before widget */
  // no \'class\' attribute - add one with the value of width
  if( strpos($before_widget, \'class\') === false ) {
    // include closing tag in replace string
    $before_widget = str_replace(\'>\', \'class="\'. $widget_width . \'">\', $before_widget);
  }
  // there is \'class\' attribute - append width value to it
  else {
    $before_widget = str_replace(\'class="\', \'class="\'. $widget_width . \' \', $before_widget);
  }
  /* Before widget */
  echo $before_widget;

  ... //other code
}
我想添加我的$widget_width 我自己的小部件代码中的小部件div元素的变量(而我可以轻松访问$widget_width 变量)。

希望这是有意义的,会帮助别人。

谢谢,Dasha

SO网友:Bainternet

您可以使用dynamic_sidebar_params 过滤钩子以查找小部件并向其添加类:

add_filter(\'dynamic_sidebar_params\', \'add_classes_to__widget\'); 
function add_classes_to__widget($params){
    if ($params[0][\'widget_id\'] == "my-widget-1"){ //make sure its your widget id here
        // its your widget so you add  your classes
        $classe_to_add = \'col480 whatever bla bla \'; // make sure you leave a space at the end
        $classe_to_add = \'class=" \'.$classe_to_add;
        $params[0][\'before_widget\'] = str_replace(\'class="\',$classe_to_add,$params[0][\'before_widget\']);
    }
    return $params;
} 

SO网友:anou

我发现为自定义小部件添加类的另一种方法是使用\'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\';
    }
}

SO网友:Satish Gandham

首先在构造函数中添加自定义占位符类

<?php
public function __construct() {
   $widget_ops  = array(
      \'classname\'                   =>; \'widget_text eaa __eaa__\', //__eaa__ is my placeholder css class
      \'description\'                 =>; __( \'AdSense ads, arbitrary text, HTML or JS.\',\'eaa\' ),
      \'customize_selective_refresh\' =>; true,
   );
   $control_ops = array( \'width\' =>; 400, \'height\' =>; 350 );
   parent::__construct( \'eaa\', __( \'Easy AdSense Ads &amp; Scripts\', \'eaa\' ), $widget_ops, $control_ops );
}
?>
然后根据如下小部件选项将其替换为您选择的类

<?php
if ( $instance[\'no_padding\'] ) {
   $args[\'before_widget\'] = str_replace( \'__eaa__\', \'eaa-clean\', $args[\'before_widget\'] );
}
?>
有关详细信息,请访问http://satishgandham.com/2017/03/adding-dynamic-classes-custom-wordpress-widgets/

SO网友:nenontwerp

您可以尝试此筛选器:

/**
 * This function loops through all widgets in sidebar 
 * and adds a admin form value to the widget as a class name  
 *  
 * @param array $params Array of widgets in sidebar
 * @return array
*/

add_filter( \'dynamic_sidebar_params\', \'nen_lib_add_class_to_widget\' );
function nen_lib_add_class_to_widget( $params )
{
    foreach( $params as $key => $widget )
    {
        if( !isset($widget[\'widget_id\']) ) continue;

        // my custom function to get widget data from admin form (object)
        $widget_data = nen_get_widget_data($widget[\'widget_id\']) ;

        // check if field excists and has value
        if( isset($widget_data->wm_name) && $widget_data->wm_name )
        {
            // convert and put value in array
            $classes = array( sanitize_title( $widget_data->wm_name ) );

            // add filter, to be able to add more
            $classes = apply_filters( \'nen_lib_add_class_to_widget\' , $classes , $widget[\'widget_id\'] , $widget , $widget_data  );

            // get \'before_widget\' element, set find and replace
            $string     = $params[$key][\'before_widget\'];
            $find       = \'"widget \';
            $replace    = \'"widget \'.implode( \' \' , $classes ).\' \';

            // new value
            $new_before = str_replace( $find , $replace , $string ) ;

            // set new value
            $params[$key][\'before_widget\'] = $new_before;
        }
    }
    return $params;
}

结束

相关推荐

Why use widgets?

我对使用WordPress很陌生,我想知道使用小部件的好处是什么?看here 这听起来像是为那些不是程序员的人准备的,他们想在他们的网站上添加插件。对吗?或者小部件是否在某种程度上使站点更加健壮?