0

I have a blog on Wordpress and I'm trying to create a button that allows anyone (even those who are not registered on the site) to like and/or unlike posts and that the current number of likes the post has received in total may appear in the button itself.

Like Button

In particular:

  • If it is not clicked, it must display the current number of likes
  • When clicked, it must increase the number by one (as well as add the CSS classes which I will then insert so that the button changes its appearance)
  • If you click a second time, the number decreases by one and the button returns to its default appearance.

Furthermore, the IP of the user who put the like should be stored so that, on subsequent accesses to the site, it is possible to view the posts that he has already voted and cannot vote again once the page has been updated.

I state that I'm not an expert and I'm trying to learn.

I followed the following tutorial: https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/?fbclid=IwAR2eRMUfWWDhoSh27nQBlbxDuhAGJdpr4Us-vuNvskRTUrvcIO-qelUdm34

Unfortunately, however, the result obtained is not as I had hoped. Also I think something is wrong in the code because I do not see the alerts. What am I doing wrong?

When the button is clicked, the number actually increases by one. If I click again, however, it increases again by one and so on ad infinitum.

How do I make it so that a single user can only add 1 vote per article? That is, if I click it the first time I add the vote, if I click it the second time I remove it, if I click it the third time I add it again and so on...

Furthermore, it should be ensured that by refreshing the page or closing the browser it is not possible to re-vote the same article, this by checking the user's IP.

Here is the code I've entered so far:

  • Code in single.php:
<?php
    $votes = get_post_meta($post->ID, "votes", true);
    $votes = ($votes == "") ? 0 : $votes;
?>
<?php
    $nonce = wp_create_nonce("my_user_vote_nonce");
    $link = admin_url('admin-ajax.php?action=my_user_vote&post_id='.$post->ID.'&nonce='.$nonce);
?>
<?php
    echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id="' . $post->ID . '" href="' . $link . '">
            <div class="like-box">              
                <div class="icon-text like-btn">                            
                    <span id="like-icon" class="icon"><i class="far fa-heart"></i></span>
                    <span id="like-text" class="text">Like</span>                                       
                    <div id="vote_counter" class="text">' . $votes .'</div>
                </div>
            </div>
        </a>'; 
?>
  • I created and activated the plugin with the following code in the .php file:
<?php

/*
    Plugin Name: Voting System
*/



add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");

function my_user_vote()
{

    if (!wp_verify_nonce($_REQUEST['nonce'], "my_user_vote_nonce")) {
        exit("No naughty business please");
    }

    $vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
    $vote_count = ($vote_count == "") ? 0 : $vote_count;
    $new_vote_count = $vote_count + 1;

    $vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);

    if ($vote === false) {
        $result['type'] = "error";
        $result['vote_count'] = $vote_count;
    } else {
        $result['type'] = "success";
        $result['vote_count'] = $new_vote_count;
    }

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $result = json_encode($result);
        echo $result;
    } else {
        header("Location: " . $_SERVER["HTTP_REFERER"]);
    }

    die();
}

function my_must_login()
{
    echo "You must log in to vote";
    die();
}




add_action('init', 'my_script_enqueuer');

function my_script_enqueuer()
{
    wp_register_script("my_voter_script", WP_PLUGIN_URL . '/voting-system/voting-system.js', array('jquery'));
    wp_localize_script('my_voter_script', 'myAjax', array('ajaxurl' => admin_url('admin-ajax.php')));

    wp_enqueue_script('jquery');
    wp_enqueue_script('my_voter_script');
}

  • Code in the plugin .js file:
jQuery(document).ready(function () {
    jQuery(".user_vote").click(function (e) {
        e.preventDefault();
        post_id = jQuery(this).attr("data-post_id");
        nonce = jQuery(this).attr("data-nonce");

    jQuery.ajax({
        type: "post",
        dataType: "json",
        url: myAjax.ajaxurl,
        data: { action: "my_user_vote", post_id: post_id, nonce: nonce },
        success: function (response) {
        if (response.type == "success") {
            jQuery("#vote_counter").html(response.vote_count);
        } else {
            alert("Your vote could not be added");
            }
        },
    });
    });
});

Thanks for any help!

Midori
  • 1
  • 1

0 Answers0