Добавление SEO-тегов для каждой страницы в Yii2 - PullRequest
0 голосов
/ 24 января 2019

Я очень новичок в этой теме.У меня есть сайт, написанный на PHP в фреймворке Yii.В моем настраиваемом CDN, где я внедряю свой контент через него, мой разработчик разработал раздел, в котором я могу назначать разные мета-теги или SEO-теги различным страницам.Моя проблема в том, что этот механизм не работает, и, на самом деле, когда я помещаю, скажем, мета-описание, он кажется, что все страницы одинаковы.Я не могу получить доступ к своему разработчику, чтобы исправить эту проблему.Ниже я предоставил коды для макета и Metadata.php.Как я уже говорил, я новичок в этой теме и не знаю, какие коды я должен предоставить для рассмотрения.Если требуется больше кодов, пожалуйста, спросите меня.

Моя цель состоит в том, чтобы исправить мою внутреннюю запись (раздел списка метаданных) так, чтобы каждая страница имела уникальные метатеги, предоставленные мной.

$metadata = \common\models\base\Metadata::find()->where(['page_routing' => 
Yii::$app->controller->id."/". Yii::$app->controller->action->id ])->one();
if ( empty($metadata ) )
$metadata = \common\models\base\Metadata::find()->where(['id' => 1 ])- 
>one();
?>

<?php $this->beginPage() ?>

<!DOCTYPE html>

<html lang="<?= Yii::$app->language ?>">

<head>
<meta charset="<?= Yii::$app->charset ?>">
<?php echo Html::csrfMetaTags() ?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, 
maximum-scale=1, user-scalable=no"/>
<meta name="robots" content="<?=$metadata->meta_robots?>"/>
<link rel="canonical" href="https://physexams.com/<?=Yii::$app->controller- 
>id."/". Yii::$app->controller->action->id?>" />
<meta property="og:image" content="<?=$metadata->og_image?>"/>
<meta property="og:title" content="<?=$metadata->og_title?>‌"/>
<meta property="og:description" content="<?=$metadata->og_description?>"/>
<meta name="twitter:image" content="<?=$metadata->twitter_image?>"/>
<meta property="og:locale" content="en_CA" />
<meta name="googlebot" content="index" />
<meta name="revisit-after" content="1 Days" />
<meta name="doc-class" content="Living Document" />
<meta name="language" content="english">
<?= Html::csrfMetaTags() ?>
<link rel="publisher" href="<?=$metadata->publisher?>" />
<title><?= Html::encode($this->title) ?></title>

<?php $this->head() ?>

Выше для краткости я вырезал другие ненужные метатеги и отправил часть кода.Если весь код необходим, я мог бы представить его.И Коды для Metadata.php

namespace common\models\base;

use Yii;

/**
 * This is the base-model class for table "metadata".
 *
 * @property integer $id
 * @property string $page_routing
 * @property string $title
 * @property string $meta_description
 * @property string $author
 * @property string $author_link
 * @property string $publisher
 * @property string $og_title
 * @property string $og_type
 * @property string $og_image
 * @property string $og_url
 * @property string $og_description
 * @property string $twitter_card
 * @property string $twitter_url
 * @property string $twitter_title
 * @property string $twitter_description
 * @property string $twitter_image
 * @property string $meta_keywords
 * @property string $meta_robots
 * @property string $meta_copyright
 * @property string $itemprop
 * @property string $Search_Display
 */
 class Metadata extends \yii\db\ActiveRecord
 {



/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'metadata';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['meta_description', 'meta_keywords', 'Search_Display'], 
'string'],
        [['page_routing', 'title', 'author', 'author_link', 'publisher', 
'og_title', 'og_type', 'og_image', 'og_url', 'og_description', 
'twitter_url', 'twitter_title', 'twitter_description', 'twitter_image', 
'meta_robots', 'meta_copyright'], 'string', 'max' => 1000],
        [['twitter_card'], 'string', 'max' => 255],
        [['itemprop'], 'string', 'max' => 2000]
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'page_routing' => 'Page Routing',
        'title' => 'Title',
        'meta_description' => 'Meta Description',
        'author' => 'Author',
        'author_link' => 'Author Link',
        'publisher' => 'Publisher',
        'og_title' => 'Og Title',
        'og_type' => 'Og Type',
        'og_image' => 'Og Image',
        'og_url' => 'Og Url',
        'og_description' => 'Og Description',
        'twitter_card' => 'Twitter Card',
        'twitter_url' => 'Twitter Url',
        'twitter_title' => 'Twitter Title',
        'twitter_description' => 'Twitter Description',
        'twitter_image' => 'Twitter Image',
        'meta_keywords' => 'Meta Keywords',
        'meta_robots' => 'Meta Robots',
        'meta_copyright' => 'Meta Copyright',
        'itemprop' => 'Itemprop',
        'Search_Display' => 'Search  Display',
    ];
}
}

Коды для Main.php в конфигурации:

return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log', 'thumbnail'],
'controllerNamespace' => 'frontend\controllers',
//'defaultRoute' => '/site/index',

'components' => [
    'request' => [
        'baseUrl' => $baseUrl,
    ],
    'urlManager' => [
        'baseUrl' => $baseUrl,
        'class' => 'yii\web\UrlManager',

        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'enableStrictParsing' => false,
        'rules' => [
            'home' => 'site/index' ,
            '/' => 'site/index', 
            'frontend/web' => 'site/index',
            'index' => 'site/index',
            'site' => 'site/index',
            'site/login' => 'site/login' ,
            'site/contact' => 'site/contact' ,
            'site/about' => 'site/about' ,
            'site/faq' => 'site/faq' ,
            'profile/logout' => 'profile/logout',
            'profile' => 'profile/index',
            'lesson/<lesson:\w+>/<id:\d+>' => 'courses/internal',
            'lesson' => 'courses/internal',

            'course/<cat:\w+>/<id:\d+>' => 'courses/index',
            'courses' => 'courses/index',

            'exam/<cat:\w+>/<id:\d+>' => 'exam/internal',
            'exam' => 'exam/index',

            'ticket' => 'ticket/index',



            'flashcard/<cat:\w+>/<id:\d+>' => 'blog/internal',
            'blog/<cat:\w+>/<id:\d+>' => 'blog/cat',
            'blog' => 'blog/index',

            '<controller:\w+>/<action:\w+>/<id:\d+>' => 
'<controller>/<action>',


        ],
        ],
    'user' => [
        'identityClass' => 'common\models\User',
        'enableAutoLogin' => true,
    ],
    'log' => [
        'traceLevel' => YII_DEBUG ? 3 : 0,
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
            ],
        ],
    ],
    'errorHandler' => [
        'errorAction' => 'site/error',
    ],

    'thumbnail' => [
        'class' => 'himiklab\thumbnail\EasyThumbnail',
        'cacheAlias' => 'assets/gallery_thumbnails',
    ],
    'assetManager' => [
        'class' => 'yii\web\AssetManager',
        'bundles' => [
                    'yii\web\JqueryAsset' => [
                        'js' => [
                            'jquery.min.js'
                        ]
                    ],

                    'yii\bootstrap\BootstrapAsset' => [
                        'css' => [
                           'css/bootstrap.min.css',
                        ]
                    ],

        ],
    ],
],
'params' => $params,
];
...