I am using WordPress. In the backend of my site, there is one sidebar. On 开发者_开发技巧this sidebar, there are n widgets. I would like to add a CSS class just in the first widget and no the rest.
How can I handle that?
Please help!
You should make dynamic sidebar that would add numbering to classes or ids of widgets. Here is nice post about it: http://wordpress.org/support/topic/how-to-first-and-last-css-classes-for-sidebar-widgets
what is it exactly that you want to change? you can put html into widgets, so you can replicate the content of your widget if it's something simple - you can also put ID-s and classes into html (and edit the css in style.css file of your theme), or you can even use css directly with style=""
tag option. if it's not something simple then it already has IDs and/or classes - so you should get those IDs and classes with firebug, and then edit the styling in style.css.
I've not had a great deal of experience with the widget hooks in WordPress, but i believe this should cover what you're asking.
<?php
if( !is_admin() ) {
$sidebar_id = 'your-sidebar-id-here';
$sidebars_array = wp_get_sidebars_widgets();
if( isset( $sidebars_array[$sidebar_id] ) && ( !empty( $sidebars_array[$sidebar_id] ) ) ) {
$first_widget = current( $sidebars_array[$sidebar_id] );
add_action( 'widgets_init', 'so4461485_widget_custom', 10000 );
}
}
function so4461485_widget_custom() {
global $wp_registered_widgets, $first_widget;
if( empty( $wp_registered_widgets ) )
return;
foreach( $wp_registered_widgets as $widget_id => $widget_data_array ) {
if( $widget_id != $first_widget )
continue;
if( isset( $widget_data_array['classname'] ) )
$wp_registered_widgets[$widget_id]['classname'] .= ' first_widget';
}
}
?>
You simply need to replace your-sidebar-id-here
(line 3 of the code) with a valid sidebar ID(that is, the ID set when the sidebar is registered).
Code can be placed inside the theme's functions.php for convenience. If you have trouble placing the code just make sure you're not nesting PHP tags.. (eg. <?php <?php
).
EDIT: The accepted answer probably addresses the question actually, so follow that advice..
Hope that helps...
精彩评论