We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 2912
    • 315 Posts
    Hi All,

    I thought I would post this up incase it was of interest.

    I came across this post: http://modxcms.com/forums/index.php/topic,1232.msg7886.html#msg7886 on my search for a hit counter that I could put into my template. I know this is not the best way of doing things as per web visits and visitors are concerned but I only need something basic for my needs.

    In the topic above there is a nice snippet called PageViews. Thanks to Starbuck for it and Kyle for modding it.

    Well I have installed PageHitCounter and after seeing the above I decided to change the PageView snippet (Sorry for keeping the same name) to the below code:

    <?php
    //Example: [[PageViews? &pageNum='47']]
    
    $piAll= 0;
    $pageNum = $modx->documentObject['id'];
    
    $table = $modx->getFullTableName("page_hit_counter");
    
    $sql = "SELECT page_count FROM $table WHERE page_id=$pageNum";
    $ds = $modx->dbQuery($sql);
    $limit = $modx->db->getRecordCount($ds);
    
    if ($limit == 0) {
      $piAll = 0;
      $times = "times";
    }
    else {
      $row = $modx->db->getRow($ds);
      $piAll = $row['page_count'];
      
         if ($piAll == 1) {
           $times = "time";
         }
         else {
            $times = "times";
         }
    }
    
    echo "<p class='totalpageviews'>This page has been viewed: $piAll $times</p>";
    ?>
    


    to fit into my template and CSS I created this style:

    .totalpageviews{
        border: 1px solid #AF2639;
        font-weight: bold;
        text-align:center;
        width:55%;
        margin:0px 100px 25px;
    }
    


    Just loving Modx more and more each day. Its a site for a friend and we hope to have it live some time in the very near future.

    UPDATE: I have changed the code so it doesnt crash if there is no record in the database (ie the page has never been viewed)
      BBloke