• Wendihihihi

    (@wendihihihi)


    I’d like to add a date based condition to the code I have to reset the counter on every Sunday 00:00:00 but I can’t figure out how to do it.

    This is what I have, but it doesn’t reset the counter to 0.

    //COUNT PAGEVIEWS
    function wpb_set_post_views($postID) {
        $count_key = 'wpb_post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        $today = date('l H:i:s');
        if($count=='' || $today == 'Sunday 00:00:00') {
            $count = 0;
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
        }else{
            $count++;
            update_post_meta($postID, $count_key, $count);
        }
    }

    Anyone with ideas?

    Thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • vtxyzzy

    (@vtxyzzy)

    The code checks for the time being exactly ‘Sunday 00:00:00’. Chances are that the code will never be executed at exactly that time.

    As an alternative, you might store the date/time of the last reset in a custom field and reset if that date is more than 7 days in the past. That way the count will show views in the last 7 days.

    Okoth1

    (@okoth1)

    There is a way to achieve this.

    Create a page, let’s say ‘reset’.
    Create a template and put this code in (assuming you have got the standard WP structure)

    <?php
    /*
    Template Name: Reset Pageviews
    */
    ?>
    <?php get_header();
    //RESET PAGEVIEW COUNTERS
    $resetallpostsviews = get_posts('numberposts=-1&post_status=any');
    
      foreach( $resetallpostsviews as $postinfo) {
        delete_post_meta($postinfo->ID, 'wpb_post_views_count');
        add_post_meta($postinfo->ID, 'wpb_post_views_count', '0');
      }
    
    $resetallpagesviews = get_pages();
    
      foreach( $resetallpagesviews as $pageinfo) {
        delete_post_meta($pageinfo->ID, 'wpb_post_views_count');
        add_post_meta($pageinfo->ID, 'wpb_post_views_count', '0');
      }
    get_footer(); ?>

    Set a cronjob, Sunday 0:00 is
    * 0 * * 0 wget http://example.com/your/url

    Add some code to your .htaccess to prevent other people then you and the host who’s doing the cronjob from going to the reset page

    RewriteEngine On
    RewriteCond %{REMOTE_ADDR} !^111\.222\.333\.444
    RewriteCond %{REMOTE_ADDR} !^999\.888\.777\.666
    RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1
    RewriteCond %{REQUEST_URI} /reset [NC]
    RewriteRule ^(.*)$ index.php [F,L]

    Et voila!

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘date based condition’ is closed to new replies.