We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 36745
    • 2 Posts
    Hello!

    I have a modx blog, and I need to add number of views to my posts.
    How can I do it / which snippet I need?

    Modx revo 2.1.3 + blog tutorial (http://rtfm.modx.com/display/revolution20/Creating+a+Blog+in+MODx+Revolution)

    thx in advance ^_^
      • 33968
      • 863 Posts
      Simplest way would be to create a new TV called pageviews. You can hide that from the manager user if you want (or even start it with an existing number of views).

      Then create a snippet also called pageviews containing this (not tested):
      <?php
      // get number of views and add current
      $views = $modx->resource->getTVValue('pageviews') + 1;
      $viewsTV = $modx->getObject('modTemplateVar',array('name' => 'pageviews'));
      // save new number of views to TV
      $viewsTV->setValue($modx->resource->get('id'), $views);
      $viewsTV->save();
      
      return $views;
      

      Then place the snippet uncached in your template where you want the number of views to appear:
      Views: [[!pageviews]]