Wordprss ajax document click statistics implementation method

Source: Internet
Author: User

In the wordpress root directory, create ajax. php as follows:

<? Php
Define ('Doing _ AJAX ', true );
Require_once ('WP-config. Php ');
Do_action ('WP _ ajax_nopriv _ '. $ _ REQUEST ['action']);
Die ('0 ');
Add the following code to functions. php in the topic directory:
// Statistics
Add_action ('WP _ ajax_nopriv_v ', 'view ');
Function views ($ echo ){
$ Post_id = intval ($ _ GET ['Views _ id']);
If ($ post_id> 0 ){
$ Post_views = get_post_custom ($ post_id );
$ Post_views = intval ($ post_views ['View'] [0]);
Update_post_meta ($ post_id, 'view', ($ post_views + 1 ));
Exit ();
    }
If ($ echo = 1 ){
Global $ post;
$ Post_ID = $ post-> ID;
$ Views = (int) get_post_meta ($ post_ID, 'view', true );
Echo number_format ($ views );
    }
}

Add the following code to the topic File footer. php:

<Script type = "text/javascript" src = "/jquery/1.8.3/jquery. min. js"> </script>

The previous section introduced the jquery library. If the original topic has been introduced, you do not need to add it again.


<? Php if (is_single () {?>
<Script type = 'text/javascript '>
/* <! [CDATA [*/var v = {"u": "\/ajax. php", "id": "<? Php the_ID ();?> "};/*]> */
JQuery. ajax ({type: "GET", url: v. u, data: "views_id =" + v. id + "& action = v "});
</Script>

After that, add the following code to the main cycle of the count to be displayed:

<Span> & hearts; <? Php views (1);?> Times </span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.