I was trying to show my most viewed post with featured image in my sidebar.php in wordpress.
I tried the following codes, but it shows one featured image repeatedly three times.
here is a link
My Codes are :
siderbar.php
<div class="popular">
<h2>Most Popular Posts</h2>
<?php echo popularPosts(3); ?>
</div>
function.php
<?php
function popularPosts($num) {
global $wpdb;
$posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , $num");
foreach ($posts as $post) {
setup_postdata($post);
$id = $post->ID;
$title = $post->post_title;
$count = $post->comment_count;
if ($count != 0) {
$popular .= '<li>';
$popular .= '<a href="' . get_permalink($id) . '" title="' . $title . '">' . $title .the_post_thumbnail(). '</a> ';
$popular .= '</li>';
}
}
return $popular;
}
?>
I've used the following code to count my post view.
function bac_PostViews($post_ID) {
//Set the name of the Posts Custom Field.
$count_key = 'post_views_count';
//Returns values of the custom field with the specified key from the specified post.
$count = get_post_meta($post_ID, $count_key, true);
//If the the Post Custom Field value is empty.
if($count == '')
{
$count = 0; // set the counter to zero.
//Delete all custom fields with the specified key from the specified post.
delete_post_meta($post_ID, $count_key);
//Add a custom (meta) field (Name/value)to the specified post.
add_post_meta($post_ID, $count_key, '0');
return $count . ' View';
//If the the Post Custom Field value is NOT empty.
}else{
$count++; //increment the counter by 1.
//Update the value of an existing meta key (custom field) for the specified post.
update_post_meta($post_ID, $count_key, $count);
//If statement, is just to have the singular form 'View' for the value '1'
if($count == '1')
{
return $count . ' View';
}
//In all other cases return (count) Views
else
{
return $count . ' Views';
}
}
}
?>
Please suggest me how can i show three most viwed page with featured image and the post title.
Aucun commentaire:
Enregistrer un commentaire