WordPress Plugin firing twice on front page but firing once on admin

I’m developing a plugin that counts user visits and saves the IP, date, and count of visits.
In DB have id(big int), IP(str), visits(int) and date(DATE).
my code in the plugin main file is this:

if (is_admin()){
    include WPS_INC . 'back-end.php';
}else{
    include WPS_INC . 'front-end.php';
    do_action('wps_update_db');
}

the code in front-end.php

function wps_user_visits_count(){
    global $wpdb;
    $tp = $wpdb->prefix;
    $today = date('Y-m-d');
    $ip = intval($_SERVER['SERVER_ADDR']);
    $is_user_visited_site_today = $wpdb->get_var("SELECT `id`
                                                        FROM `{$tp}wps_user_visits` 
                                                        WHERE `date` = '{$today}' AND `ip` = {$ip}");
    if (empty($is_user_visited_site_today)){
        $wpdb->insert($tp . 'wps_user_visits',
        array(
            'ip' => $ip,
            'date' => $today
        ),
        array(
            '%d','%s'
        ));
    }else{
        $wpdb->query("UPDATE `{$tp}wps_user_visits`
                      SET `visits` = `visits` + 1
                      WHERE `id` = {$is_user_visited_site_today}");
    }
}

add_action('wps_update_db','wps_user_visits_count');

and it will add 2 visits in DB instead of one.
in this line SET `visits` = `visits` + 1 for example, if I change 1 to 3, it will add 6 visits instead of 3.

how can I solve this problem?

I also use $wpdb->update. no change.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The problem was NOT with the code.

The problem was with the Wampserver.

So if you are using wampserver, get a backup of your database and www folder and then DELETE wampserver using REVO UNINSTALLER. It’s so important using this program for uninstallation.

After the first step of uninstallation, you should delete all left-overs using the Revo uninstaller.

After that, you can easily install wampserver and you are good to go.

I should say that I was using a virtual host too. So if you used it, my answer will probably help you.

If you are using another local host program such as XAMP and Laragon, try this solution.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x