lundi 20 avril 2015

Insert query not working for non-logged in user in wordpress

I am trying to create a function for count post views. for this i have added code in my function file.

Here is my code:

function processpost_views( ){
        global $user_ID, $post;
        if( is_int( $post ) ) {
            $post = get_post( $post );
        }
    if( !wp_is_post_revision( $post ) )
    {
        if( is_single() || is_page() )
        {
            $id = intval( $post->ID );
            global $post;

            $date = explode('-', date('W-d-m-Y', current_time('timestamp')));
                foreach (array(
                0 => $date[3].$date[2].$date[1],    // day like 20140324
                1 => $date[3].$date[0],             // week like 201439
                2 => $date[3].$date[2],             // month like 201405
                3 => $date[3],                      // year like 2014
                4 => 'total'                        // total views
                ) as $type => $period)
                {
                insertView($post->ID, $type, $period, 1);
                }
        }
    }

}

second function

function insertView( $id, $type, $period, $count = 1 ) {

    global $wpdb;
        $wpdb->postviews = "{$wpdb->prefix}postviews";
        $wpdb->test = "{$wpdb->prefix}test";
        $count = (int) $count;      

        if ( ! $count ) {
            $count = 1;
        }
        $sql = $wpdb->prepare("
                INSERT INTO " . $wpdb->prefix . "postviews (id, type, period, count)
                VALUES (%d, %d, %s, %d)
                ON DUPLICATE KEY UPDATE count = count + %d",
                $id,
                $type,
                $period,
                $count,
                $count
            );      

        $wpdb->query($sql);


}

add_action( 'wp_head', 'processpost_views' );

In this above code, my insert and update queries work i am logged in but when i am guest/ logged user this code not work. Please help me.

Aucun commentaire:

Enregistrer un commentaire