| 1 |
<?php |
| 2 |
/** |
| 3 |
* Frontend feed setup. |
| 4 |
* |
| 5 |
* @copyright (c) 2021, Code Atlantic LLC. |
| 6 |
* @package ContentControl |
| 7 |
*/ |
| 8 |
|
| 9 |
namespace ContentControl\Controllers\Frontend; |
| 10 |
|
| 11 |
defined( 'ABSPATH' ) || exit; |
| 12 |
|
| 13 |
use ContentControl\Base\Controller; |
| 14 |
|
| 15 |
use WP_Customize_Manager; |
| 16 |
|
| 17 |
use function ContentControl\is_rest; |
| 18 |
use function ContentControl\protection_is_disabled; |
| 19 |
use function ContentControl\user_meets_requirements; |
| 20 |
use function ContentControl\Widgets\get_options as get_widget_options; |
| 21 |
|
| 22 |
/** |
| 23 |
* Class ContentControl\Frontend\Widgets |
| 24 |
*/ |
| 25 |
class Widgets extends Controller { |
| 26 |
|
| 27 |
/** |
| 28 |
* Initialize Widgets Frontend. |
| 29 |
*/ |
| 30 |
public function init() { |
| 31 |
add_filter( 'sidebars_widgets', [ $this, 'exclude_widgets' ] ); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Checks for and excludes widgets based on their chosen options. |
| 36 |
* |
| 37 |
* @param array<string,array<string>> $widget_areas An array of widget areas and their widgets. |
| 38 |
* |
| 39 |
* @return array<string,array<string>> The modified $widget_area array. |
| 40 |
*/ |
| 41 |
public function exclude_widgets( $widget_areas ) { |
| 42 |
if ( is_rest() || protection_is_disabled() || $this->is_customize_preview() ) { |
| 43 |
return $widget_areas; |
| 44 |
} |
| 45 |
|
| 46 |
foreach ( $widget_areas as $widget_area => $widgets ) { |
| 47 |
if ( ! empty( $widgets ) && 'wp_inactive_widgets' !== $widget_area ) { |
| 48 |
foreach ( $widgets as $position => $widget_id ) { |
| 49 |
$options = get_widget_options( $widget_id ); |
| 50 |
|
| 51 |
// If no options, then skip this one. |
| 52 |
if ( empty( $options['which_users'] ) ) { |
| 53 |
continue; |
| 54 |
} |
| 55 |
|
| 56 |
// If not accessible then exclude this item. |
| 57 |
|
| 58 |
/** |
| 59 |
* Filter whether to exclude a widget. |
| 60 |
* |
| 61 |
* @param bool $exclude Whether to exclude the widget. |
| 62 |
* @param array $options Widget options. |
| 63 |
* @param string $widget_id Widget ID. |
| 64 |
* |
| 65 |
* @return bool |
| 66 |
*/ |
| 67 |
$exclude = apply_filters( |
| 68 |
'content_control/should_exclude_widget', |
| 69 |
! user_meets_requirements( $options['which_users'], $options['roles'] ), |
| 70 |
$options, |
| 71 |
$widget_id |
| 72 |
); |
| 73 |
|
| 74 |
// unset non-visible item. |
| 75 |
if ( $exclude ) { |
| 76 |
unset( $widget_areas[ $widget_area ][ $position ] ); |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
return $widget_areas; |
| 83 |
} |
| 84 |
|
| 85 |
/** |
| 86 |
* Is customizer. |
| 87 |
* |
| 88 |
* @return boolean |
| 89 |
*/ |
| 90 |
public function is_customize_preview() { |
| 91 |
global $wp_customize; |
| 92 |
|
| 93 |
return ( $wp_customize instanceof WP_Customize_Manager ) && $wp_customize->is_preview(); |
| 94 |
} |
| 95 |
} |
| 96 |
|