我在函数中使用此代码。php跟踪帖子视图。
/* Functions to track Post Views*/
function getPostViews($postID){
$count_key = \'post_views\';
$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.\' view\';
}
function setPostViews($postID) {
$count_key = \'post_views\';
$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);
}
}
/* Track the Views for the post using wp_head hook */
function trackPostViews ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
setPostViews($post_id);
}
add_action( \'wp_head\', \'trackPostViews\');
但我想在侧边栏上显示我浏览次数最多的帖子,这是行不通的。有显示的帖子,但不是浏览最多的。这是我的问题。
<?php
function filter_where2($where = \'\') {
$where .= " AND post_date > \'" . date(\'Y-m-d\', strtotime(\'-10 days\')) . "\'";
return $where;
}
if ( ! $my_paged = absint( get_query_var( \'paged\' ) ) )
$my_paged = 1;
if ( ! $my_query = get_transient( "7677recent_$my_paged" ) )
{
add_filter(\'posts_where\', \'filter_where2\');
$my_query = new WP_Query( "meta_key=post_views&orderby=meta_value&order=DESC&posts_per_page=5&paged=$my_paged" );
set_transient( "7677recent_$my_paged", $my_query, 60 * 60 );
}
remove_filter( \'posts_where\', \'filter_where2\' );
while ($my_query->have_posts()) : $my_query->the_post();
?>