使用AJAX在缓存站点上更新自定义帖子字段

时间:2013-07-24 作者:Zen Nguyễn

我的网站由“wp SuperCache”插件和“cloudflare.com”缓存

因此,我的php函数可以计算工作不正常的帖子视图。

我尝试使用ajax,但我不懂JS代码,所以我不知道哪里错了。

在里面functions.php 我创建了一个简单的函数:

add_action(\'template_redirect\', \'ajax_activation\');
function ajax_activation(){
   //optional 
   wp_enqueue_script( 
      \'ajax_script\', 
       get_template_directory_uri() . \'/js/ajax.js\', // path to your js file for ajax operations
       array( \'jquery\' ), false
   );
   //end optional
   wp_localize_script( 
      \'ajax_script\', // the name of your global.js registered file
      \'ajax_object\', // name 
       array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) // you can add other items for example for using a translated string in javascript/jquery context
   ); 
}

add_action(\'wp_ajax_get_PostViews\', \'get_PostViews\');
add_action(\'wp_ajax_nopriv_get_PostViews\', \'get_PostViews\');

function get_PostViews() {
$id = isset( $_POST[\'id\'] ) ? $_POST[\'id\'] : false;
$count_key = \'post_views_count\'; 
$count = get_post_meta($post_ID, $count_key, true);
if( empty($count) ){ $count = 1; } else { $count++; }
update_post_meta($post_ID, $count_key, $count);
}
代码输入ajax.js 文件:

var postID = $(".view_detail").attr("id");
jQuery.ajax({
    type: "POST",
    url: ajax_object.ajaxurl, // this is the object you defined in function.php
    data: {
       action: \'get_PostViews\', // the name of your function
       id: postID // you can store it in html attribute for an easy access like: jQuery(element).attr(\'id\');
    },
    success: function (result) {
    }
});
Thepage.php 在我的主题中:

<div id="<?php the_ID(); ?>" <?php post_class(\'view_detail\'); ?>>
请告诉我怎样才能工作?非常感谢!

3 个回复
最合适的回答,由SO网友:iEmanuele 整理而成

我在这里发现了一些错误:

jQuery.ajax({
     type: "POST",
     contentType: "application/json; charset=utf-8", // default: \'application/x-www-form-urlencoded; charset=UTF-8\'. you can not set
     url: "http://localhost/wp-admin/admin-ajax.php", // if you have correctly enabled ajax in wp, you should use the object you set up with the url
     data: "{\'action\':\'get_PostViews(" + idpost + ")\'}", // you can use a PlainObject notation, so you don\'t need to double quoted. action property is the name of your function as you written in function.php
     success: function (result) {
       alert(\'Update Success!\');
     }
});
看看这里jQuery.ajax() .要在WordPress中使用ajax,请执行以下步骤:

启用ajax功能在函数中声明函数。php使用javascript/jquery将数据发送到服务器并侦听检索到的数据

Enabling ajax

在我看来,实现这一目标的最佳方式是:

//File functions.php
    add_action(\'template_redirect\', \'ajax_activation\');
    function ajax_activation(){
       //optional 
       wp_enqueue_script( 
          \'ajax_script\', 
           get_template_directory_uri() . \'/js/jquery.ajax.js\', // path to your js file for ajax operations
           array( \'jquery\' ), false
       );
       //end optional
       wp_localize_script( 
          \'ajax_script\', // the name of your global.js registered file
          \'ajax_object\', // name 
           array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) // you can add other items for example for using a translated string in javascript/jquery context
       ); 
    }
Declare function

//File functions.php
add_action(\'wp_ajax_get_PostViews\', \'get_PostViews\');
add_action(\'wp_ajax_nopriv_get_PostViews\', \'get_PostViews\');

function get_PostViews() {
    $id = isset( $_POST[\'id\'] ) ? $_POST[\'id\'] : false;
    // your code here
    wp_die(); // | die(); you need this to avoid trailing zero
}

jQuery/Javascript

$.ajax({
    type: "POST",
    url: ajax_object.ajaxurl, // this is the object you defined in function.php
    data: {
       action: \'get_PostViews\', // the name of your function
       id: // you can store it in html attribute for an easy access like: jQuery(element).attr(\'id\');
    },
    success: function (result) {

    }
});
我猜您正在对循环中的所有帖子使用此函数,您可以调用ajax一次来完成所有帖子的工作。例如,我想用ajax检索我帖子的标题:

HTML

<html>
<!-- some stuff here -->
<h3 id="<?php echo get_the_ID(); ?>" class="spyhole"></h3> <!-- there are many of this :  ) -->
<!-- some stuff here -->
</html>
jQuery

ids = [];
items = $(\'.spyhole\');
$.each( items, function( i, v){
    ids.push( $(v).attr( \'id\' ) ); // each value is added to array
});
$.ajax({
    type: "POST",
    url: ajax_object.ajaxurl,
    data: {
      action: \'getMyTitleAjax\',
      id: ids
    },
    success: function (result) {
      data = $.parseJSON( result ); // Takes a well-formed JSON string and returns the resulting JavaScript object.
      $.each( data, function( i, v ){
        $(\'.spyhole[id="\' + i + \'"]\').html( v ); // print the title
      });
    }
});
PHP

// Enabling ajax - functions.php
add_action(\'template_redirect\', \'ajax_activation\');
function ajax_activation(){
   //optional 
   wp_enqueue_script( 
      \'ajax_script\', 
       get_template_directory_uri() . \'/js/jquery.ajax.js\', // path to your js file for ajax operations
       array( \'jquery\' ), false
   );
   //end optional
   wp_localize_script( 
      \'ajax_script\', // the name of your global.js registered file
      \'ajax_object\', // name 
       array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) // you can add other items for example for using a translated string in javascript/jquery context
   ); 
}

// Declare my function
add_action(\'wp_ajax_getMyTitleAjax\', \'getMyTitleAjax\', 3);
add_action(\'wp_ajax_nopriv_getMyTitleAjax\', \'getMyTitleAjax\', 3);
function getMyTitleAjax() {
    $ids = isset( $_POST[\'id\'] ) ? $_POST[\'id\'] : false; // check if there is something in global $_POST
    if( $ids && is_array( $ids ) ){
      foreach( $ids as $id ){
        $titles[$id] = get_the_title( $id ); 
      }
    }
    echo json_encode( $titles ); // prints the result
    wp_die(); // avoid trailing zero
}
希望有帮助,如果有什么不清楚的地方,请尽管问

Update

根据您的问题更新,更改此选项:

function get_PostViews() {
$id = isset( $_POST[\'id\'] ) ? $_POST[\'id\'] : false;
$count_key = \'post_views_count\'; 
$count = get_post_meta($post_ID, $count_key, true);
if( empty($count) ){ $count = 1; } else { $count++; }
update_post_meta($post_ID, $count_key, $count);
}
使用此选项:

function get_PostViews() {
$id = isset( $_POST[\'id\'] ) ? $_POST[\'id\'] : false;
$count_key = \'post_views_count\'; 
$count = get_post_meta($id, $count_key, true);
if( empty($count) ){ $count = 1; } else { $count++; }
update_post_meta($id, $count_key, $count);
}

SO网友:ji_feraou

single.php

// ------------Post  views----------          
<script type="text/javascript">
    // get post views
    (function($) {
        function mostViews() {
             $.getJSON("<?php bloginfo(\'template_directory\'); ?>/ajax.php",
                    {
                        action: \'get_mostViewedPost\',
                        postid: <?php echo get_the_ID() ?>
                    }, function (data) {
                    })
        }
        var mostViews = new mostViews();
    })(jQuery);

</script>
functions.php

// ------------Post  views----------
// function to display number of posts.
function getPostViews($postID){
    $count_key = \'post_views_count\';
    $count = get_post_meta($postID, $count_key, true);
    if($count==\'\'){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, \'0\');
        return "0 View";
    }
    return $count.\' Views\';
}

// function to count views.
function setPostViews($postID) {
    $count_key = \'post_views_count\';
    $count = get_post_meta($postID, $count_key, true);
    if($count==\'\'){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, \'0\');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

// Add it to a column in WP-Admin
add_filter(\'manage_posts_columns\', \'posts_column_views\');
add_action(\'manage_posts_custom_column\', \'posts_custom_column_views\',5,2);
function posts_column_views($defaults){
    $defaults[\'post_views\'] = __(\'Views\');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
    if($column_name === \'post_views\'){
        echo getPostViews(get_the_ID());
    }
}

function postViews_callback(){
    setPostViews($_GET[\'postid\']) ;
    echo "Success, Post id: ".$_GET[\'postid\'];
    die();
}
add_action(\'ajax_get_mostViewedPost\', \'postViews_callback\');
add_action(\'ajax_nopriv_get_mostViewedPost\', \'postViews_callback\');

// -----------end Post views----------

ajax.php

<?php
//mimic the actuall admin-ajax
define(\'DOING_AJAX\', true);

//make sure you update this line
//to the relative location of the wp-load.php

require_once(dirname(dirname(dirname(dirname($_SERVER[\'SCRIPT_FILENAME\'])))) . \'/wp-load.php\');
//Typical headers
header(\'Content-Type: text/html\');
send_nosniff_header();

//Disable caching
header(\'Cache-Control: no-cache\');
header(\'Pragma: no-cache\');

$action = esc_attr(trim($_GET[\'action\']));


//A bit of security
$allowed_actions = array( 
    \'get_mostViewedPost\'
);

//For logged in users 
add_action(\'ajax_get_mostViewedPost\', \'postViews_callback\');
//For guests 
add_action(\'ajax_nopriv_get_mostViewedPost\', \'postViews_callback\');

if(in_array($action, $allowed_actions)) {
    if(is_user_logged_in())
        do_action(\'ajax_\'.$action);
    else
        do_action(\'ajax_nopriv_\'.$action);
} else {
    die(\'-1\');
}

SO网友:ji_feraou

single.php //post views

   <script type="text/javascript">  
        // get post views  
        (function($) {  
            function mostViews() {  
                 $.getJSON("<?php bloginfo(\'template_directory\'); ?>/ajax.php",  
                        {  
                            action: \'get_mostViewedPost\',  
                            postid: <?php echo get_the_ID() ?>  
                        }, function (data) {  
                        })  
            }  
            var mostViews = new mostViews();  
        })(jQuery);  

    </script>
functions.php

// ------------Post  views----------  
// function to display number of posts.  
function getPostViews($postID){  
    $count_key = \'post_views_count\';  
    $count = get_post_meta($postID, $count_key, true);  
    if($count==\'\'){  
        delete_post_meta($postID, $count_key);  
        add_post_meta($postID, $count_key, \'0\');  
        return "0 View";  
    }  
    return $count.\' Views\';  
} 
// function to count views.  
function setPostViews($postID) {  
    $count_key = \'post_views_count\';  
    $count = get_post_meta($postID, $count_key, true);  
    if($count==\'\'){  
        $count = 0;  
        delete_post_meta($postID, $count_key);  
        add_post_meta($postID, $count_key, \'0\');  
    }else{  
        $count++;  
        update_post_meta($postID, $count_key, $count);  
    }  
} 

// Add it to a column in WP-Admin  
add_filter(\'manage_posts_columns\', \'posts_column_views\');  
add_action(\'manage_posts_custom_column\', \'posts_custom_column_views\',5,2);  
function posts_column_views($defaults){  
    $defaults[\'post_views\'] = __(\'Views\');  
    return $defaults;  
} 
function posts_custom_column_views($column_name, $id){  
    if($column_name === \'post_views\'){  
        echo getPostViews(get_the_ID());  
    }  
} 
function postViews_callback(){  
    setPostViews($_GET[\'postid\']) ;  
    echo "Success, Post id: ".$_GET[\'postid\'];  
    die();  
}  
add_action(\'ajax_get_mostViewedPost\', \'postViews_callback\');  
add_action(\'ajax_nopriv_get_mostViewedPost\', \'postViews_callback\'); 

// -----------end Post views----------  
ajax.php

 <?php  
    //mimic the actuall admin-ajax  
    define(\'DOING_AJAX\', true);  



    //make sure you update this line  
    //to the relative location of the wp-load.php  

    require_once(dirname(dirname(dirname(dirname($_SERVER[\'SCRIPT_FILENAME\'])))) . \'/wp-load.php\');
    //Typical headers  
    header(\'Content-Type: text/html\');  
    send_nosniff_header();  

    //Disable caching  
    header(\'Cache-Control: no-cache\');  
    header(\'Pragma: no-cache\');  

    $action = esc_attr(trim($_GET[\'action\']));  


    //A bit of security  
    $allowed_actions = array(   
        \'get_mostViewedPost\'
    );  

    //For logged in users   
    add_action(\'ajax_get_mostViewedPost\', \'postViews_callback\');  
    //For guests 
    add_action(\'ajax_nopriv_get_mostViewedPost\', \'postViews_callback\');

    if(in_array($action, $allowed_actions)) {  
        if(is_user_logged_in())  
            do_action(\'ajax_\'.$action);  
        else  
            do_action(\'ajax_nopriv_\'.$action);  
    } else {  
        die(\'-1\');  
    }

结束

相关推荐

BATCACHE/Memcated页面缓存组合中的APC对象缓存?

在岗位上WordPress Caching Comparisons Part 2 Matt Martz比较了不同的缓存设置,其中包括APC object caching 连同Batcache 页面缓存。在他的帖子中,这种组合似乎是设置复杂性和效率之间的最佳权衡。他没有提到memcached,所以我不确定它是否被使用过。阅读马克·贾奎斯的帖子APC Object Cache Backend for WordPress 在我看来,他的插件就像一个嵌入式替换后端,用来代替memcached,这就是Batcach