nickcernis
10/13/2015 - 12:36 PM

Count widgets that are active for the current WPML language

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;
}