I’m using keremiya theme for wordpress. I was trying to display my most viewed post in my custom post type if “most_viewed” option is on. The name of my custom post type is watch. How can i do this with my current code? I am also using a plugin called wp-post views to display the views in my sidebar. Here is my query.
<?php if(get_option('most_viewed') == 'On'): ?>
<div class="sidebar-right">
<h2><?php echo get_option('my_title'); ?></h2>
<div class="fimanaortala">
<?php $tavsayi = get_option('keremiya_tavsiyesayi'); $tavkat = get_option('keremiya_tavsiyekat');?>
<?php query_posts('showposts='.$tavsayi.'&v_orderby=desc&cat='.$tavkat.'') ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="filmana">
<div class="filmsol">
<?php keremiya_resim('80px', '70px', 'izlenen-resim'); ?>
</div>
<div class="filmsag">
<div class="filmsagbaslik">
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
</div>
<div class="filmsagicerik">
<?php if(function_exists('the_views')) { the_views(); echo " "; } ?>
<p><?php nezaman_yazildi(); ?></p>
</div>
<div class="filmizleme">
<a href="<?php the_permalink() ?>"><img src="<?php bloginfo('template_directory'); ?>/images/filmizle.png" alt="film izle" height="21" width="61" /></a>
</div>
</div>
</div>
<?php endwhile; else: ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
</div>
</div>
Your solution (or attempt, at least), is based on a plugin called WP-PostViews, which I have no knowledge of. So, I can’t really help you there. I can, however, help you solve it without this or any other plugin. So here we go:
WordPress has a little something called metadata. From this very own link:
That means you can create metadata for your custom post type that contains how many times it has been seen. To do so, we create a function:
This will, given the post ID, increment a counter every time a post is viewed. Of course, we have to call this function somewhere in our code so it actually runs. You can do this in two ways: You can either call this function on your single template (which I believe is called single-watch.php), or you can add a simple tracker. I favor the second option, as it keeps your single post loop cleaner. You can achieve such tracking this way:
There you go. Now, WordPress checks if the user is visiting a page corresponding to a watch single post. If they are, it increments the counter.
The only thing left now is to query for the post with the highest number of views. This is easily achievable using
WP_Query
. When you create your loop, do something like this:I kept my answer to PHP, so you can adapt to your mark-up needs. I also assumed your post-type is indeed called watch. I hope all of this helps you. If you want to query your posts in a slightly different way, I suggest you read the WP_Query docs. Cheers.