Skip to content

Instantly share code, notes, and snippets.

@nickcernis
Last active August 6, 2020 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickcernis/7bae855040d0f821d333 to your computer and use it in GitHub Desktop.
Save nickcernis/7bae855040d0f821d333 to your computer and use it in GitHub Desktop.
Count widgets that are active for the current WPML language
<?php
/**
* Count widgets in a given sidebar, taking WPML language switching into account.
*
* Assumes widget languages are switched with the WPML String Translation or WPML Widgets plugins.
*
* @param string $id The sidebar ID.
*
* @return int The count of widgets in the sidebar.
*/
function wpml_count_widgets( $id ) {
global $sidebars_widgets, $wp_registered_widgets;
$count = 0;
if ( isset( $sidebars_widgets[ $id ] ) ) {
foreach ( $sidebars_widgets[ $id ] as $widget_id ) {
// Check widget visibility as set by WPML
$widget_options = get_option( 'widget_' . $wp_registered_widgets[ $widget_id ]['callback'][0]->id_base );
$widget_number = preg_replace( '/[^0-9.]+/i', '', $widget_id );
$current_widget_options = $widget_options[ $widget_number ];
$widget_wpml_language = array(
$current_widget_options['icl_language'],
$current_widget_options['wpml_language']
);
$widget_wpml_language = array_filter( array_unique( $widget_wpml_language ) );
// Count the widget if it has no language setting or its language setting matches the current active language
if ( ! defined( 'ICL_LANGUAGE_CODE' ) || empty( $widget_wpml_language ) || in_array( ICL_LANGUAGE_CODE, $widget_wpml_language ) || in_array( 'all', $widget_wpml_language ) ) {
$count ++;
}
}
}
return $count;
}
@nickcernis
Copy link
Author

N.B. This doesn't yet take other visibility settings into account, like widgets hidden with the Jetpack Widget Visibility module or other filtered widgets.

@hauge75
Copy link

hauge75 commented Apr 11, 2016

Shouldn't it be: if ( ! defined( 'ICL_LANGUAGE_CODE' ) ?

@nickcernis
Copy link
Author

@hauge75 That condition is present at the beginning of this line:

if ( ! defined( ICL_LANGUAGE_CODE ) || empty( $widget_wpml_language ) || in_array( ICL_LANGUAGE_CODE, $widget_wpml_language ) || in_array( 'all', $widget_wpml_language ) )

Which means, “if the widget has no language setting or is set to appear in all widgets”, count it.

@hauge75
Copy link

hauge75 commented Apr 11, 2016

I mean: shouldn't ICL_LANGUAGE_CODE be in single quotes when you check if its defined?
(http://php.net/manual/en/function.defined.php)

@nickcernis
Copy link
Author

@hauge75 Ah – thanks for that. Updated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment