stevenslack
4/26/2016 - 11:32 AM

If sidebar has a text widget with a particular shortcode

If sidebar has a text widget with a particular shortcode

<?php
/**
 * Check the sidebar or sidebars for a shortcode
 *
 * @param  mixed array|string|int $index sidebar id, name, or an array of sidebar names
 * @param  string $shortcode the shortcode to check for
 * @return bool true if the sidebar contents contains the shortcode, false otherwise
 */
function if_sidebar_has_shorcode( $index, $shortcode ) {
	// get all the sidebars widgets
	$sidebars_widgets = get_option( 'sidebars_widgets' );
	// where we'll put our list of widget ids
	$widget_ids = array();

	// if index is not an array cast it as one
	if ( ! is_array( $index ) ) {
		$index = array( $index );
	}

	foreach ( $index as $sidebar ) {
		// skip to next sidebar if there are no widgets
		if ( ! is_active_sidebar( $sidebar ) ) {
			continue;
		}
		// get all widgets in sidebar by ID
		$widgets = $sidebars_widgets[ $sidebar ];

		// grab only text widgets
		foreach ( $widgets as $widget_id ) {
			if ( false !== stripos( $widget_id, 'text-' ) ) {
				$widget_ids[] = ltrim( $widget_id, 'text-' );
			}
		}
	}

	if ( ! empty( $widget_ids ) ) {
		// get all the text widgets from the options table
		$widget_texts = get_option( 'widget_text' );

		foreach ( $widget_ids as $widget_id ) {
			// cast each widget id as a widget instance
			if ( isset( $widget_texts[ $widget_id ] ) && $instance = $widget_texts[ $widget_id ] ) {

				// check for the shortcode and make sure widget is scheduled to display
				if ( has_shortcode( $instance['text'], $shortcode ) ) {
					$show_widget = true;

					// shortcircuit if Jetpack widget visibility module is false
					if ( class_exists( 'Jetpack_Widget_Conditions' ) ) {
						$show_widget = ( $show_widget && Jetpack_Widget_Conditions::filter_widget( $instance ) );
					}

					return $show_widget;
				}
			}
		}
	}

	return false;
}