-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmz-post-views.php
59 lines (47 loc) · 1.23 KB
/
kmz-post-views.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
/*
Plugin Name: KMZ Page Views
Description: Simple plugin for count post views
Plugin URI: https://wpdev.pp.ua
Author: Vladimir Kamuz
Author URI: https://wpdev.pp.ua
Text Domain: kmz-post-views
Version: 1.0.0
*/
include(dirname(__FILE__) . '/kmz-functions.php');
/**
* Add new field in the DB table wp_posts
*/
register_activation_hook(__FILE__, 'kmz_post_create_field');
function kmz_post_create_field(){
global $wpdb;
if( !kmz_has_field($wpdb->posts, 'post_views') ){
$query = "ALTER TABLE $wpdb->posts ADD post_views INT NOT NULL DEFAULT '0'";
$wpdb->query($query);
}
}
/**
* Output posts views after content on Blog pages
*/
add_filter('the_content', 'kmz_post_views');
function kmz_post_views($content){
if(is_page()) return $content;
global $post;
$views = $post->post_views;
return $content . "<p><b>Views:</b> " . $views . "</p>";
}
/**
* Add view and save it in the DB after go to single post
*/
add_action('wp_head', 'kmz_add_view');
function kmz_add_view(){
if(!is_single()) return;
global $post, $wpdb;
$id = $post->ID;
$views = $post->post_views += 1;
$wpdb->update(
$wpdb->posts,
array('post_views' => $views),
array('ID' => $id)
);
}