1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Need a little help with this wordpress code

Discussion in 'PHP' started by Divvy, Oct 10, 2015.

  1. #1
    Hello guys,

    Maybe someone can help me...
    I want to display most popular posts by views of each category...
    I already have a code but is not working like I want, is displaying from ALL categories.

    Here is my code in single.php file:

    <?php
    foreach(get_the_category(get_the_ID()) as $keys){
        $cu = $keys->cat_name;
    }
    ?>
    <h2 class="single-post-external" style="background: #9F0C67; padding: 8px 0 8px 8px;">Most Viewed Posts in <?php echo $cu; ?> Category<?php //echo  "Like ".get_the_title(); ?></h2>  
        <?php setPostViews(get_the_ID()); ?>
        <?php query_posts('posts_per_page=8&meta_key=post_views_count&orderby=meta_value_num&order=DESC'); ?>
        <div id="main_container" class="mrCatouter container  clearfix">
        <?php while ( have_posts() ) : the_post(); ?>
    PHP:
    And in my functions.php file I have this:
    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); 
        }
    }
    
    PHP:
    I found out that adding a &cat= after DESC and enter the id number for the category it works. Example:
    <?php query_posts('posts_per_page=8&meta_key=post_views_count&orderby=meta_value_num&order=DESC&cat=2'); ?>
    Code (markup):
    But I dont want to show a specific category, I want to show the category where the post is in...
    Any ideas?

    Hope to see some help here :)

    Thank you guys!
     
    Solved! View solution.
    Divvy, Oct 10, 2015 IP
  2. #2
    Put the query inside the foreach, and limit the result by 1 - > will fetch the top viewed post for each category (you'll of course need to use the cat= category_id_from_loop)
     
    PoPSiCLe, Oct 10, 2015 IP
  3. Divvy

    Divvy Well-Known Member

    Messages:
    771
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    128
    #3
    Fixed!! Thank you my friend :D
    You're my savior again :)
     
    Divvy, Oct 11, 2015 IP