• Resolved saeki013

    (@saeki013)


    I would like to record the number of views with “Post Views Counter” for articles that are displayed in accordion format.
    However, currently, the following code does not add the number of views.
    How should I describe it to make it work?

    footer.php

    jQuery(document).ready(function($) {
        $('.faq-item').click(function() {
            var post_id = $(this).data('post-id');
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'update_post_views',
                    post_id: post_id
                },
                success: function(response) {
                    console.log('Post views updated');
                }
            });
        });
    });

    functions.php

    add_action('wp_ajax_update_post_views', 'update_post_views');
    add_action('wp_ajax_nopriv_update_post_views', 'update_post_views');
    function update_post_views() {
        if (is_user_logged_in()) {
            die();
        }
    
        if (isset($_POST['post_id'])) {
            $post_id = intval($_POST['post_id']);
            $post_views = get_post_meta($post_id, 'post_views', true);
            $post_views = ($post_views == '') ? 1 : intval($post_views) + 1;
            update_post_meta($post_id, 'post_views', $post_views);
        }
        die();
    }

    If there is anything that needs to be improved, please let me know.
    Thank you!

Viewing 1 replies (of 1 total)
  • Thread Starter saeki013

    (@saeki013)

    I solved that issue on my own.
    The following code solved.

    jQuery(document).ready(function($) {
        $('.faq-item').click(function() {
            var faq_post_id = $(this).data('post-id');
            var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    
            var xhr = new XMLHttpRequest();
            xhr.open('POST', ajaxurl);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log('Post views updated. ID: ' + faq_post_id);
                }
            };
            xhr.send('action=update_post_views&post_id=' + faq_post_id);
        });
    });
    function update_post_views() {
        $post_id = $_POST['post_id'];
        pvc_get_post_views( $post_id, 'total' );
        $post_views = ($post_views == '') ? 1 : $post_views + 1;
        pvc_update_post_views( $post_id, $post_views);
    	wp_die();
    }
    add_action('wp_ajax_nopriv_update_post_views', 'update_post_views');
Viewing 1 replies (of 1 total)
  • The topic ‘I would like to record the number of views in accordion format using ajax’ is closed to new replies.