Add activity log for WordPress

Plugin: Albert Plugin Extension

Files:

albert.php
visit-log.php

Get user IP location

API: http://tools.211cn.ca/api/iplocation.php

$api = "http://tools.211cn.ca/api/iplocation.php";
$url = $api . "?ip=" . get_the_user_ip();
$loc = wp_remote_get($url);
if( is_wp_error( $loc ) ) return false;

$body = wp_remote_retrieve_body( $loc );
$data = json_decode( $body );
if( ! empty( $data ) ) {
	$city = $data->City;
	$country = trim(explode('(',trim($data->Country,' '))[0],' ');
}

Get page type

if(is_front_page() || is_home()){  //home
	$type='home';
	$id = 0;
}
elseif(is_category()){  //category
	$type = 'category';
	$id = get_query_var('cat');
}
else {  //page,post
	$type = get_post_type();
	$id = get_the_ID();
	if($id=='' || $id==0) $id = $post->id;
	if($id==0) return;
}

Complete solution

function log_activity(){
    global $wp,$wpdb,$post;
    wp_reset_postdata();

    $api = "http://tools.211cn.ca/api/iplocation.php";
    $url = $api . "?ip=" . get_the_user_ip();
    $loc = wp_remote_get($url);
    if( is_wp_error( $loc ) ) return false;
    
    $body = wp_remote_retrieve_body( $loc );
    $data = json_decode( $body );
    if( ! empty( $data ) ) {
        $city = $data->City;
        $country = trim(explode('(',trim($data->Country,' '))[0],' ');
    }

    if(is_front_page() || is_home()){  //home
        $type='home';
        $id = 0;
    }
    elseif(is_category()){  //category
        $type = 'category';
        $id = get_query_var('cat');
    }
    else {  //page,post
        $type = get_post_type();
        $id = get_the_ID();
        if($id=='' || $id==0) $id = $post->id;
        if($id==0) return;
    }

    $sql = "INSERT INTO wp_moove_activity_log (post_id, user_id, status, user_ip, city,country, post_type, referer, month_year, display_name,visit_date) VALUES
    ('".$id."','".get_current_user_id()."','visited','".get_the_user_ip()."','$city','$country','$type','".wp_get_referer()."','".get_the_date('mY')."','". wp_get_current_user()->display_name. "','".current_time( 'mysql', 1 )."');";
    $result = $wpdb->get_results($sql);

    $sql = "insert into wp_sql (post_id,`sql`,date) values ('".$id."','".addslashes($sql)."','".current_time( 'mysql', 1 )."');";
    $result = $wpdb->get_results($sql);

    return $result;
}
add_action( 'template_redirect', 'log_activity' );

Enable plugin

Done.

Note:

This is replacement of the plugin “User Activity Tracking and Log“. This plugin log pages and posts visits, but does not log every visit.

The new custom plugin reuse the table wp_moove_activity_log of “User Activity Tracking and Log” plugin.

17 total views, 2 views today

Leave a Reply