0

I am trying to create click counter with Ajax for login users. I have multiple subscriber in the blog and need to count there clicks.

HTML:

<a id="countable" href="#">Click Counter</a>
<?php 
    $current_user = wp_get_current_user();
    echo get_user_meta($current_user, 'click_counter', true); 
?>

Function.php

<?php
add_action( 'wp_ajax_click_counter', 'click_counter');
add_action( 'wp_ajax_nopriv_click_counter', 'click_counter' );
function click_counter() {
    $current_user =  wp_get_current_user();
    if ( isset( $_POST['nonce'] ) &&  isset( $_POST[$current_user->ID] ) && wp_verify_nonce( $_POST['nonce'], 'click_counter_' . $_POST[$current_user->ID] ) ) {
        $count = get_user_meta( $_POST[$current_user->ID], 'click_counter', true );
        update_user_meta( $_POST[$current_user->ID], 'click_counter', ( $count === '' ? 1 : $count + 1 ) );
    }
    exit();
}

add_action( 'wp_footer', 'click_head' );
function click_head() {
    $current_user = wp_get_current_user();
    if( isset( $current_user->ID ) ) {
?>
    <script type="text/javascript" >
    jQuery(function ($) {
        var ajax_options = {
            action: 'click_counter',
            nonce: '<?php echo wp_create_nonce( 'click_counter_' . $current_user->ID ); ?>',
            ajaxurl: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
            $current_user: '<?php echo $current_user->ID; ?>'
        };

        $( '#countable' ).on( 'click', function() {
            var self = $( this );
            $.post( ajax_options.ajaxurl, ajax_options, function() {
                window.location.href = self.attr( "href" );
            });
            return false;
        });
    });
    </script>
<?php
    }
}?>

This code not giving me any type of output or error.

What I am missing in this code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.