dowdw44426 2014-10-12 00:40
浏览 29

在wordpress上编码ajax点击计数器

i need help coding an ajax click counter for wordpress.... i have tried for a few days and can't seem to figure it out. i have a template page that lists a custom post type and displays mixtapes/albums and all of them are downloadable. the template page is coded in php so the links are a variable and not static html. i need to create a counter that counts and displays how many times each download link is clicked.... so a click counter....

this is the code for a link on the template page.

<a href="<?php echo get_post_meta($post->ID,'mixtape_link',true); ?>" class="button small"><span>Download Now!</span></a>

i have tried tons of scripts and plugins and cant seem to figure it out.

if someone could post an example code or do this for me it would be greatly appreciated

  • 写回答

1条回答 默认 最新

  • dtzk85937 2014-10-12 02:28
    关注

    html:

    <a href="<?php echo get_post_meta($post->ID,'mixtape_link',true); ?>" id="thisdownloads" class="button small"><span>Download Now!</span></a>
    
    <script>
        jQuery(document)ready(function() {
    
          jQuery(this).on('change', '#thisdownloads', function() {
    
            jQuery.ajax({
            type: "POST",
            url: "/wp-admin/admin-ajax.php",
    
            data: {
                action: 'update_downloads',
                ID: '<?php get_the_ID(); ?>'// if within the loop you need a correct id for this to work...........
            },
            success: function (output) {}
               console.log(output);
            });
    
    
          });
        });
    
    </script>
    

    php:

        add_action('wp_ajax_update_downloads', 'update_downloads');
    add_action('wp_ajax_nopriv_update_downloads', 'update_downloads');
    
    function update_downloads() {
    
      $id= sanitize_text_fields($_POST['ID']);
    
      $downloads= get_post_meta($id,'_downloads',true);
    
      if(!$downloads):
         $downloads=1;
      else:
         $downloads++;
      endif;
    
      update_post_meta($id,'_downloads', $downloads);
      echo $downloads;
      exit();
    
    }
    

    should be close enough, if you cant make this work you need to research the following:

    1. jquery "on" change
      2.jquery safe mode (wordpress)
    2. jquery ajax wordpress
    3. wordpress ajax functions add action
    4. update_post_meta
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决