-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.php
88 lines (71 loc) · 1.92 KB
/
handlers.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
function set_post_likes()
{
global $wpdb;
$table = $wpdb->get_blog_prefix() . 'post_likes';
$type = $_POST['type'];
$post_id = $_POST['post_id'];
$is_like = 0;
$user_ip = $_SERVER['REMOTE_ADDR'];
$url = $_POST['url'];
$timestamp = date('Y-m-d H:i:s');
switch ($type) {
case 'like':
$is_like = 1;
break;
case 'dislike':
$is_like = -1;
break;
}
$sql = <<<SQL
INSERT INTO $table (post_id, is_like, user_ip, url, timestamp)
VALUES (%d, %d, %s, %s, %s) ON DUPLICATE KEY UPDATE
post_id = %d,
is_like = %d,
user_ip = %s,
url = %s,
timestamp = %s
SQL;
$vars = [$post_id, $is_like, $user_ip, $url, $timestamp, $post_id, $is_like, $user_ip, $url, $timestamp];
$wpdb->get_results($wpdb->prepare($sql, $vars));
$response;
if (!$wpdb->last_error) {
$response = [
'success' => true,
'new_rating' => get_post_likes($post_id),
];
} else {
$response = [
'success' => false,
];
}
echo json_encode($response);
wp_die();
}
function get_posts_likes()
{
global $wpdb;
$table = $wpdb->get_blog_prefix() . 'post_likes';
$user_ip = $_SERVER['REMOTE_ADDR'];
$sql = <<<SQL
SELECT
post_id,
SUM(is_like) as total,
SUM(case when user_ip = '$user_ip' then is_like else 0 end) as user
FROM $table
GROUP BY post_id;
SQL;
return $wpdb->get_results($sql, OBJECT_K);
}
function get_post_likes($post_id)
{
global $wpdb;
$table = $wpdb->get_blog_prefix() . 'post_likes';
$sql = <<<SQL
SELECT SUM(is_like) as total
FROM $table
WHERE post_id = '%d'
GROUP BY post_id;
SQL;
return $wpdb->get_results($wpdb->prepare($sql, (int) $post_id))[0]->total;
}