· 8 years ago · Apr 17, 2018, 02:00 AM
1<?php
2
3function filter_where($where = '') {
4 //posts in the last 30 days
5 $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
6 return $where;
7}
8add_filter('posts_where', 'filter_where');
9
10query_posts('post_type=post&posts_per_page=4&orderby=rand&order=DESC');
11
12while (have_posts()): the_post(); ?>
13
14<li style="
15 margin-bottom: 5px;
16 background: transparent url(http://i.imgur.com/6ngfnNo.png) repeat scroll center top;
17 padding: 15px;
18 list-style-type: none;
19 width: 500px;
20 margin: 10px 0px 0px 10px;
21"><a href="<?php the_permalink(); ?>" title="<?php printf(esc_attr('Permalink to %s'), the_title_attribute('echo=0')); ?>" rel="bookmark"><span class="tptn_title" style="
22 color: #fff;
23 text-transform: uppercase;
24 font-family: 'Montserrat-Bold', sans-serif;
25"><?php the_title(); ?></span></a></li>
26
27<?php
28endwhile;
29wp_reset_query();
30?>
31
32<?php
33// creating the post views DB table
34add_action('wp_head', 'create_post_views_table');
35function create_post_views_table() {
36 global $wpdb;
37 // our table name
38 $table_name = $wpdb->prefix . "post_views";
39 // SQL for creating the table
40 $sql = "CREATE TABLE IF NOT EXISTS $table_name (
41 meta_id int(11) NOT NULL AUTO_INCREMENT,
42 post_id int(11) NOT NULL,
43 date_viewed datetime NOT NULL,
44 PRIMARY KEY (meta_id)
45 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";
46 // we're using functions from the WP admin
47 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
48 // executing the SQL
49 dbDelta($sql);
50}
51?>
52
53<?php
54// Add this function when user sees the post / most likely in single.php or loop-single etc.
55
56// recording each post view
57function update_post_views($postID) {
58 global $wpdb;
59 // our table name
60 $table_name = $wpdb->prefix . "post_views";
61 // the current time
62 $date = date('Y-m-d H:i:s');
63 // the SQL for inserting the view
64 $sql = "INSERT INTO $table_name (post_id,date_viewed) VALUES ($postID, '$date')";
65 // executing the SQL
66 $wpdb->query($sql);
67}
68?>
69
70<?php
71// get the most popular posts for the last X days
72function get_most_popular_posts($count = 30, $interval = '') {
73 global $wpdb;
74 $where = '';
75 // adding WHERE clause to specify the date interval
76 if ($interval) {
77 $where = "
78 WHERE date_viewed > ( NOW() - INTERVAL $interval DAY)
79 ";
80 }
81 // building SQL
82 $sql = "SELECT post_id, COUNT(post_id) as count
83 FROM {$wpdb->prefix}post_views
84 {$where}
85 GROUP BY post_id
86 ORDER BY count DESC
87 LIMIT $count
88 ";
89 // fetching the posts
90 $results = $wpdb->get_results($sql);
91 return $results;
92}
93?>