Widgets - nikonorovsv/wpf GitHub Wiki
All parts in the WPF that you want to display on the page are recommended to be formatted as widgets. A widget is an object of a class inherited from the \wpf\base\Widget
class. Widget classes should be located in the /app/widgets
folder. Widgets can generate their own html, or use templates. You can override $this->render()
method to return html without using of templete. Let's look at the code.
namespace app\widgets;
use \wpf\base\Widget;
class SomeWidget extends Widget {
public $template = 'widget';
public function __construct( array $conf = [] ) {
parent::__construct( $conf );
$this->title = 'Some title';
$this->content = 'Some text';
}
public function render():string {
return parent::render();
}
}
Templates should be located in /app/views
folder and look like this:
// Declare defaults. They will be replace with values defined by widget.
extract( [
'title' => '',
'content' => ''
], EXTR_SKIP ); ?>
<div class="widget">
<div class="widget-title">
<?= $title ?>
</div>
<div class="widget-content">
<?= $content ?>
</div>
</div>
Widgets can use \wpf\wp\QueryBuilder
trait for easy way to include some query to DB.
namespace app\widgets;
use \wpf\base\Widget;
use \wpf\wp\QueryBuilder;
class SomeWidget extends Widget {
use QueryBuilder;
public $template = 'widget';
public function __construct( array $conf = [] ) {
parent::__construct( $conf );
$this->items = $this->query()->posts;
}
public function queryArgs(): array {
return [
'post_type' => 'custom_post_type',
'post_status' => 'publish',
'posts_per_page' => 10
];
}
}
Next, you simply call the widget in the right place. The passed parameters will be available as class properties after the parent constructor is called. Then you can do with them whatever you want.
use \app\widgets\SomeWidget;
echo (string) new SomeWidget([
'title' => 'Some title',
'content' => 'Some text'
]);
Also you can use wpf_widget() function to call widget.
echo wpf_widget('\app\widgets\SomeWidget', [
'title' => 'Some title',
'content' => 'Some text'
]);