Saltern
Saltern

Reputation: 1383

create site map in yii2

i want create site map in yii2 I do not know what I would do. Help me Where do I start? this is my news model :

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

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['news_cat_id', 'user_id','time'], 'integer'],
        [['news_dec'], 'string'],
        [['news_title', 'logo'], 'string', 'max' => 255]
    ];
}

i cant work with extension because that haven't good document.

Upvotes: 2

Views: 2890

Answers (1)

Vitaly
Vitaly

Reputation: 1281

  1. Install package composer require evert/sitemap-php
  2. Create command Controller for console app in @app/commands/ directory.

    class SitemapController extends Controller {

    public function actionIndex(){
    
        $host = 'http://yoursitehost.com/';
    
        $sitemap = new Sitemap($host);
    
        $sitemap->setPath(Yii::getAlias('@webroot').DIRECTORY_SEPARATOR);
    
        $sitemap->addItem('', '1.0', 'daily', 'Today');
        $sitemap->addItem('news', '9.0', 'daily', 'Today');
    
        foreach(News::find()->batch(50) as $news){
            foreach($news as $n){
                $sitemap->addItem(Url::toRoute(['news/view', 'id' => $n->id]), '8.0', 'daily', 'Today');
            }
        }
    
        $sitemap->createSitemapIndex($host, 'Today');
    }
    

    }

  3. Add your controller to console.php config file.

    $config = [ ... 'controllerMap' => [ 'sitemap' => [ 'class' => 'app\commands\SitemapController' ], ] ];

And add to top console.php Yii::setAlias('@webroot', dirname(__DIR__) . '/../web');

  1. Run command php yii sitemap. Script generate file sitemap.xml to web directory.

  2. Go to link - http://yourhost.com/sitemap.xml.

You can run this command php yii sitemap by cron.

Upvotes: 1

Related Questions