在wordpress根目录下,新建ajax.php.内容如下
<?php
define( 'DOING_AJAX', true );
require_once( 'wp-config.php' );
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
die( '0' );
在主题目录下的functions.php添下以下代码:
//统计
add_action( 'wp_ajax_nopriv_v', 'views' );
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['views'][0] );
update_post_meta( $post_id, 'views', ( $post_views + 1 ) );
exit();
}
if ($echo == 1) {
global $post;
$post_ID = $post->ID;
$views = (int)get_post_meta($post_ID, 'views', true);
echo number_format($views);
}
}
在主题文件footer.php适当位置添加以下代码:
<script type="text/javascript" src="/jquery/1.8.3/jquery.min.js"></script>
上面一段引入jquery库,如原主题已有引入,就不用再添加了.
<?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>
完毕,接下来在需要显示的计数的主循环内添加以下代码即可:
<span>♥ <?php views(1);?>次</span>