Đầu tiên bạn hãy sao chép đoạn code bên dưới rồi dán vào file function.php trong thư mục theme mà bạn đang sử dụng.
// them huu ich va tam duoc vao bai viet cua caodem
function ip_post_likes($content) {
if(is_singular('post')) {
ob_start();
?>
<div class="yes-likes">
<div class="title-like">Chào <?php echo $current_user->nickname; ?>! Bạn thấy nội dung này thế nào? </div>
<div class="ok-like">
<a href="<?php echo add_query_arg('post_action', 'like'); ?>">Hữu ích <?php echo ip_get_like_count('likes') ?></a>
<a href="<?php echo add_query_arg('post_action', 'dislike'); ?>">Tạm được <?php echo ip_get_like_count('dislikes') ?></a>
</div>
</div>
<?php
$output = ob_get_clean();
return $content . $output;
}else {
return $content;
}
}
add_filter('the_content', 'ip_post_likes');
function ip_get_like_count($type = 'likes') {
$current_count = get_post_meta(get_the_id(), $type, true);
return ($current_count ? $current_count : 0);
}
function ip_process_like() {
$processed_like = false;
$redirect = false;
if(is_singular('post')) {
if(isset($_GET['post_action'])) {
if($_GET['post_action'] == 'like') {
$like_count = get_post_meta(get_the_id(), 'likes', true);
if($like_count) {
$like_count = $like_count + 1;
}else {
$like_count = 1;
}
$processed_like = update_post_meta(get_the_id(), 'likes', $like_count);
}elseif($_GET['post_action'] == 'dislike') {
$dislike_count = get_post_meta(get_the_id(), 'dislikes', true);
if($dislike_count) {
$dislike_count = $dislike_count + 1;
}else {
$dislike_count = 1;
}
$processed_like = update_post_meta(get_the_id(), 'dislikes', $dislike_count);
}
if($processed_like) {
$redirect = get_the_permalink();
}
}
}
if($redirect) {
wp_redirect($redirect);
die;
}
}
add_action('template_redirect', 'ip_process_like');
Tiếp theo dán đoạn css bên dưới vào file style.css trong thư mục theme mà bạn đang sử dụng.
.ok-like a {
margin-right: 10px;
text-decoration: none;
color: #111;
font-size: 13px;
font-weight: bold;
background:#fff444;
padding:5px 8px 5px 8px;
border-radius:7px;
display: inline-block;
}
.ok-like a:hover{color:#fff;background:#0c0}
.title-like{color:#ccc;font-size:15px;}
.yes-likes {
padding: 20px;
background: #4b238a;
text-align: center;
border-radius: 10px;
}
@media (max-width: 400px){
.ok-like a{font-size:10px}
}
Như vậy là bài viết của bạn đã có thêm nút hưu ích và tạm được để người đọc có thể bình chọn rồi đó.
Chúc bạn thành công!
HIỆN TẠI CÓ 0 BÌNH LUẬN
Một số lưu ý khi bình luận
Mọi bình luận sai nội quy sẽ bị xóa mà không cần báo trước (xem nội quy)
Bấm Thông báo cho tôi bên dưới khung bình luận để nhận thông báo khi admin trả lời
Để bình luận một đoạn code, hãy mã hóa code trước nhé