From 0863a80a27da1add6fca6bc575ef28e3ab6056c0 Mon Sep 17 00:00:00 2001 From: Brandon Date: Thu, 24 Oct 2024 06:18:52 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20`Widget::show()`=20method=20t?= =?UTF-8?q?o=20control=20widget=20visibility=20when=20rendering=20(#287)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🎨 Small widget code clean up --- src/Widget.php | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/Widget.php b/src/Widget.php index 6d30136c..a426f2b2 100644 --- a/src/Widget.php +++ b/src/Widget.php @@ -73,9 +73,7 @@ public function compose() $this->register(function () { $this->widget = (object) collect( Arr::get($GLOBALS, 'wp_registered_widgets') - )->filter(function ($value) { - return $value['name'] === $this->name; - })->pop(); + )->filter(fn ($value) => $value['name'] === $this->name)->pop(); }); add_filter('widgets_init', function () { @@ -86,24 +84,25 @@ public function compose() } /** - * Returns an instance of WP_Widget used to register the widget. - * - * @return WP_Widget + * Determine if the widget should be displayed. + */ + public function show(): bool + { + return true; + } + + /** + * Create a new WP_Widget instance. */ - protected function widget() + protected function widget(): WP_Widget { return new class($this) extends WP_Widget { /** * Create a new WP_Widget instance. - * - * @param \Log1x\AcfComposer\Widget $composer - * @return void */ - public function __construct($composer) + public function __construct(public Widget $composer) { - $this->composer = $composer; - parent::__construct( $this->composer->slug, $this->composer->name, @@ -122,6 +121,10 @@ public function widget($args, $instance) { $this->composer->id = $this->composer->widget->id = Str::start($args['widget_id'], 'widget_'); + if (! $this->composer->show()) { + return; + } + echo Arr::get($args, 'before_widget'); if (! empty($this->composer->title())) {