SEO Behavior
Seo behavior for Yii2 models and meta tags helper, (*1)
Installing
composer require --prefer-dist laco-agency/seo-behavior
or add, (*2)
"laco-agency/seo-behavior": "*"
to the require section of your composer.json., (*3)
Usage
Model:, (*4)
use laco/seo/SeoModelBehavior;
public function behaviors()
{
return [
[
'class' => SeoModelBehavior::className(),
'descriptionFromAttribute' => 'teaser',
'metaImageAttribute' => 'image_preview'
]
]
}
Controller:, (*5)
use laco/seo/SeoControllerBehavior;
Attach behavior:, (*6)
public function behaviors()
{
return [
SeoControllerBehavior::className()
];
}
In case when parent controller already has behaviors, you can attach SeoControllerBehavior like this:, (*7)
public function behaviors()
{
$behaviors = [
'access' => [
'class' => AccessControl::className(),
'rules' => []
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => []
]
];
return array_merge(parent::behaviors(), $behaviors);
}
Or like this:, (*8)
public function init()
{
$this->attachBehavior('seo', SeoControllerBehavior::className());
}
Action:, (*9)
In the action use the method $this->setMetaTags($model) and pass $model as parameter;, (*10)
public function view($slug)
{
$model = Material::findOne(['slug' => $slug]));
$this->setMetaTags($model);
}
Or use an array in this format instead of model:, (*11)
[
'metaTitle' => 'Custom meta title',
'metaDescription' => 'Custom description',
'metaImage' => 'Custom meta image'
]