Skip to content

Instantly share code, notes, and snippets.

@stevenslack
Created April 26, 2016 11:32
Show Gist options
  • Save stevenslack/880e6b6099429529ed9a059cf20068f9 to your computer and use it in GitHub Desktop.
Save stevenslack/880e6b6099429529ed9a059cf20068f9 to your computer and use it in GitHub Desktop.
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;
}
@tjtaylo
Copy link

tjtaylo commented Jan 8, 2019

Thank you sir!!!

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