I would like to record the number of views in accordion format using ajax
-
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)
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.