Skip to content

Commit

Permalink
✨ Add Widget::show() method to control widget visibility when rende…
Browse files Browse the repository at this point in the history
…ring (#287)

🎨 Small widget code clean up
  • Loading branch information
Log1x authored Oct 24, 2024
1 parent ad270cb commit 0863a80
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions src/Widget.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand All @@ -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,
Expand All @@ -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())) {
Expand Down

0 comments on commit 0863a80

Please sign in to comment.