Last active
October 15, 2015 22:01
-
-
Save eduardozulian/49ba07a71dcf71e9a7c9 to your computer and use it in GitHub Desktop.
WordPress hook that loops through widget areas and add some custom classes for each one of them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Loop through widget areas and add custom classes for each one of them | |
* | |
* @link http://colourstheme.com/2015/03/add-class-to-first-and-last-widget/ Reference #1 | |
* @link https://gist.github.com/slobodan/6156076 Reference #2 | |
*/ | |
function fltnt_add_widget_custom_classes() { | |
global $wp_registered_widgets; | |
// Find those widgets | |
$sidebars = wp_get_sidebars_widgets(); | |
if ( empty ( $sidebars ) ) { | |
return; | |
} | |
// Loop through each widget area | |
foreach ( $sidebars as $sidebar_id => $widgets ) { | |
// Our main sidebar doesn't need additional classes | |
if ( 'sidebar-main' == $sidebar_id ) { | |
continue; | |
} | |
// Get the number of widgets on the sidebar | |
$number_of_widgets = count( $widgets ); | |
foreach ( $widgets as $i => $widget_id ) { | |
$widget_classes = ''; | |
$widget_position = ( $i + 1 ); | |
// Add a class for widget position | |
$widget_classes .= ' widget-position-' . $widget_position; | |
// Add a class for the total number of widgets in this widget area | |
$widget_classes .= ' widget-count-' . $number_of_widgets; | |
// Add first widget class | |
if ( 1 == $widget_position ) { | |
$widget_classes .= ' widget-first'; | |
} | |
// Add last widget class | |
if ( $number_of_widgets == $widget_position ) { | |
$widget_classes .= ' widget-last'; | |
} | |
// Add specific Foundation classes for layouts with, respectively, 6, 4, 3 or 2 columns | |
if ( 6 == $number_of_widgets ) { | |
$widget_classes .= ' medium-2'; | |
} | |
elseif ( 4 == $number_of_widgets ) { | |
$widget_classes .= ' medium-3'; | |
} | |
elseif ( 3 == $number_of_widgets ) { | |
$widget_classes .= ' medium-4'; | |
} | |
elseif ( 2 == $number_of_widgets ) { | |
$widget_classes .= ' medium-6'; | |
} | |
else { | |
$widget_classes .= ' medium-12'; | |
} | |
// Add Foundation columns | |
$widget_classes .= ' columns'; | |
// Save new classes into global $wp_registered_widgets | |
$wp_registered_widgets[$widget_id]['classname'] .= $widget_classes; | |
} | |
} | |
} | |
add_action( 'init', 'fltnt_add_widget_custom_classes' ); |
Great! Exactly what I was searching, thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice