Skip to content

Instantly share code, notes, and snippets.

@nickcernis
Last active August 6, 2020 14:39
Show Gist options
  • 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

@hauge75 Ah – thanks for that. Updated!

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