首页 > 解决方案 > 在 WordPress 上编写 AJAX 点击计数器

问题描述

我正在研究 WordPress 上的 ajax 点击计数器。当用户点击时,它会显示点击次数。我的代码:

html

<?php 
    $link_download = get_field('link_download');
?>
<a href="<?php echo $link_download ?>" id="taive" >DownLoad</a>
<span id="counter"></span>

计数器.js

(function($) {
    $(document).ready(function() {
        $('#taive').click(function() {
            $.ajax({
                type: "POST",
                dataType: 'json',
                url: "/wp-admin/admin-ajax.php",
                data: {
                    action: 'set_download',
                    ID: '<?php get_the_ID(); ?>'
                },
                cache: false,
                async: false,
                success: function(response) {
                    if (response.error.message) {
                            alert(response.error.message);
                        } else if (response.success) {
                            jQuery('#count').html(response.data);
                        }
                }
            });

        });
    });
})

函数.php

function js_enqueue_scripts() {
wp_enqueue_script ("my-ajax-handle", get_stylesheet_directory_uri() . "/js/counter.js", array('jquery')); 
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' =>admin_url('admin-ajax.php')));
} 
add_action("wp_enqueue_scripts", "js_enqueue_scripts");

add_action('wp_ajax_set_download', 'set_download');
add_action('wp_ajax_nopriv_set_download', 'set_download');

function set_download() {

  $downloads= get_post_meta($post->ID,'count',true);

  if(!$downloads):
     $downloads=1;
  else:
     $downloads++;
  endif;

  update_post_meta($post->ID,'count', $downloads);

  echo $downloads;

  exit();
};

我想在 id="counter" 上显示点击次数,我该怎么做?

标签: ajaxwordpress

解决方案


推荐阅读