Search code examples
phpajaxwordpressadmin-ajax

Calling PHP function in Wordpress through admin-ajax.php not updating meta information, but receive a success message


post_views_count() is meant to update the view count of the page current postID using an ajax request so it can still work.

When called it is outputting that is has been successfully called but when debugging my view count is being added. Any help would be appreciated.

FYI: This is on a custom post type called courses.


Code within functions.php

add_action('wp_ajax_nopriv_post_views_count', 'post_views_count');
add_action('wp_ajax_post_views_count', 'post_views_count');

function post_views_count() {
    global $wpdb;
    $countKey = 'post_views_count';
    $count = get_post_meta($postID, $countKey, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $countKey);
        add_post_meta($postID, $countKey, '0');
    }else{
        $count++;
        update_post_meta($postID, $countKey, $count);
    }
    exit();
}

Code within single-courses.php

<script>
        jQuery(document).ready(function() {
            var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
            jQuery.ajax({
            type: "POST",
            cache: false,
            url: ajaxurl,
            data: {
                action: 'post_views_count',
                postID: '<?php echo get_the_ID(); ?>'
            },
            success: function (output) {
                console.log("<?php echo get_post_meta(get_the_ID(), 'post_views_count', true); ?>");
            }

            }); 
        });
    </script>

Solution

  • Solved!

    Sent a request for the postID data and can now track the post view count when the page is statically cached.

    $postID = $_REQUEST['postID'];