Reputation: 23
I'm working on a site trying to get a popular posts section on it. I've tried plugins but they require wp_head() and that destroys the jCarousel that I have on the site. I've implemented the code to getPostViews with the following in functions.php:
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 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);
}
}
However when I insert the following in a loop to display it, my site goes down telling me that I need to install wordpress again. When I go through with the installation, I get a list of database errors. However, if I go back to it some time later in the day with the code removed, the site works again.
<? query_posts('meta_key=post_views_count&orderby=meta_value_num&order=DESC'); ?>
How can I get the popular posts to work using this? Or is there another way I should be looking at to get popular posts to work? Thanks for the help.
Upvotes: 2
Views: 10557
Reputation: 690
Pleace this in functions.php:
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 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);
}
}
Next, place this where you'd like to return the post list w/views:
<ul>
<?php
global $post;
$args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<li><?php setPostViews(get_the_ID()); echo getPostViews(get_the_ID());; ?></li>
<?php endforeach; ?>
</ul>
Upvotes: 2