Last active
August 6, 2020 14:39
-
-
Save nickcernis/7bae855040d0f821d333 to your computer and use it in GitHub Desktop.
Count widgets that are active for the current WPML language
This file contains 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 | |
/** | |
* 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; | |
} |
Shouldn't it be: if ( ! defined( 'ICL_LANGUAGE_CODE' ) ?
@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.
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)
@hauge75 Ah – thanks for that. Updated!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.