Thêm nút Bắn tim cho bài viết WordPress sử dụng ACF

Nếu bạn muốn thêm nút Bắn tim cho bài viết WordPress để tăng độ tương tác, bài viết này sẽ giúp bạn.

Thêm nút Bắn tim cho bài viết WordPress sử dụng ACF

Các bài viết cần tham khảo:

ACF

Bạn cần tạo trường lưu dữ liệu tim bài viết như sau.

acf-post-like

HTML

Đầu tiên, bạn cần thêm thẻ chứa icon trái tim và số lượng tim hiện tại của bài viết tại single.php.

<?php
    $like_num = get_field('post_like');
    if (!$like_num) $like_num = 0;
?>
<div class="text-center"><button class="icobutton" data-post="<?php echo get_the_ID(); ?>"><span class="glyphicon glyphicon-heart"></span><span class="like-number"><?php echo $like_num; ?></span></button></div>

CSS

Thêm đoạn CSS sau để giao diện dễ nhìn hơn.

.icobutton {
    font-size: 70px;
    position: relative;
    margin: 0 0 0 -50px;
    padding: 50px 55px 35px 50px;
    color: #c0c1c3;
    border: 0;
    width: 300px;
    background: none;
    overflow: hidden;
}

@media (max-width: 480px) {
    .icobutton {
        margin: 0;
    }
}

.icobutton.active {
    color: #f35186;
}

.like-number {
    font-size: 16px;
    padding: 5px 10px;
    font-weight: 700;
    margin-top: -20px;
    position: absolute;
    top: 95px;
    left: 200px;
    background: #eee;
    border-radius: 6px;
}

.like-number:after {
    right: 100%;
    top: 50%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-color: rgba(244, 245, 247, 0);
    border-right-color: #eee;
    border-width: 7px;
    margin-top: -7px;
}

.icobutton:hover,
.icobutton:focus {
    outline: none;
}

PHP

Thêm phương thức xử thả tim lí tại functions.php.

/**
 * Thả tim bài viết
 */
add_action('wp_ajax_like', 'like_post');
add_action('wp_ajax_nopriv_like', 'like_post');
function like_post() {
	$like = intval(get_field('post_like', $_POST['post']));
	if (!$like) $like = 0;
	$like++;
	update_field('post_like', $like, $_POST['post']);

	$data = array('like' => $like);
	wp_send_json_success($data);
    die();
}

JavaScript

Bạn thêm mo.js để tạo hiệu ứng cho icon trái tim nhé.

<script src="https://cdn.jsdelivr.net/mojs/latest/mo.min.js"></script>

Cuối cùng, thêm phương thức xử lí khi bấm thả tim vào footer.php.

var initAjax = '<?php echo admin_url('admin-ajax.php'); ?>';

$(document).ready(function() {
    // Kiểm tra người dùng có thả tim bài viết này chưa
    var likeList = JSON.parse(localStorage.getItem("likeList")) || [];
    var liked = 0;
    if (likeList.length > 0) {
        for (var i = 0; i < likeList.length; i++) {
            if (likeList[i] == $('#single-title').text()) { // Với $('#single-title') là thẻ chứa tiêu đề bài viết
                liked = 1;
                break;
            }
        }
    }

    // Nếu có, tắt chức năng thả tim
    if (liked == 1) {
        $('.icobutton').addClass('active');
    }

    var scaleCurve = mojs.easing.path('M0, 100 L25, 99.9999983 C26.2328835, 75.0708847 19.7847843, 0 100, 0');
    var el = document.querySelector('.icobutton'),
    elSpan = el.querySelector('span'),
    timeline = new mojs.Timeline(),
    tween1 = new mojs.Burst({
    parent : el,
        duration : 2500,
        shape : 'circle',
        fill : ['#f35186'],
        opacity : 0.6,
        childOptions : {radius : {20 : 0}},
        radius : {40 : 120},
        count : 10,
        isSwirl : true,
        easing : mojs.easing.bezier(0.1, 1, 0.3, 1)
    }),
    tween2 = new mojs.Transit({
        parent : el,
        duration : 450,
        type : 'circle',
        radius : {0 : 50},
        fill : 'transparent',
        stroke : '#f35186',
        strokeWidth : {18 : 0},
        opacity : 0.6,
        easing : mojs.easing.bezier(0, 1, 0.5, 1)
    }),
    tween3 = new mojs.Tween({
        duration : 550,
        onUpdate : function(progress) {
            var scaleProgress = scaleCurve(progress);
            elSpan.style.WebkitTransform = elSpan.style.transform = 'scale3d(' + scaleProgress + ', ' + scaleProgress + ', 1)';
        }
    });

    timeline.add(tween1, tween2, tween3);

    el.addEventListener('click', function() {
        if (!$(this).hasClass('active')) {
            timeline.replay();
            $(this).addClass('active');
            $.ajax({
                type: 'post',
                dataType: 'json',
                url: initAjax,
                data: {
                    'action': 'like',
                    'post': $(this).data('post')
                },
                success: function(response) {
                    if(response.success) {
                        $('.like-number').html(response.data.like);
                        // Lưu thông tin bài viết vào danh sách thả tim
                        var likeList = JSON.parse(localStorage.getItem("likeList")) || [];
                        likeList.unshift($('#single-title').text()); // Với $('#single-title') là thẻ chứa tiêu đề bài viết
                        likeList = likeList.filter(onlyUnique);
                        localStorage.setItem("likeList", JSON.stringify(likeList));
                    }
                }
            });
        }
    });
});

function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
}

Chúc các bạn thành công!

Bình luận


2 bình luận
  • Admin

    14/07/2024 lúc 16:59

    mình đã gắn các đoạn code vào chính bài viết này và đã chạy được, nên nếu có gì ko hiểu cứ để lại câu hỏi nhé ❤️

    • Người Qua Đường

      14/07/2024 lúc 17:18

      nice

Init Toolbox

Nhấn Ctrl + \ trên máy tính, hoặc vuốt sang trái ở bất kỳ đâu trên mobile.

Đăng nhập





Đang tải...