简体   繁体   中英

Popular Posts Not Showing Through WP_query

I want to make sidebar as per user requirements but in this sidebar user want to show popular posts of blog and I do more searching to show it but all its vain. :( Here is my code!

<div class="ms_recent">
    <h5>Popular posts</h5>
    <?php
    $blog_papular = array(
        'posts_per_page'=>5,
        'meta_key' => 'wpb_post_views_count',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
    );

    $wp_query_papular=new WP_Query($blog_papular);

    while($wp_query_papular->have_posts()) {
        $wp_query_papular->the_post();
        ?>
        <div class="ms_articles">
            <a href="<?php the_permalink(); ?>">
                <?php the_post_thumbnail('footer_page_image'); ?>
                <span><?php echo get_the_date('F j'); ?></span>
                <p><?php echo excerpt('8'); ?></p></a>
        </div>
        <?php
    }
    ?>
</div>

Here anyone know where I mistaken?

After digging WordPress more and more I know my fault. The fault is that meta key value is not stored in database that's why my popular posts not showing. I take just few steps to do that Here is:

First thing we need to do is create a function that will detect post views count and store it as a custom field for each post:

 function wpb_set_post_views($postID) {
$count_key = 'wpb_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);
}
}

remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Secondly I paste the following code inside my single post loop:

wpb_set_post_views(get_the_ID());

Then my blog loop is to show the popular posts:

 <?php
    $blog_papular = array(
        'posts_per_page'=>5,
        'meta_key' => 'wpb_post_views_count',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
    );
    $wp_query_papular=new WP_Query($blog_papular);
    while($wp_query_papular->have_posts())
    {
        $wp_query_papular->the_post();
        ?>
        <div class="ms_articles">
            <a href="<?php the_permalink(); ?>">
                <?php the_post_thumbnail('footer_page_image'); ?>
                <span><?php echo get_the_date('F j'); ?></span>
                <p><?php echo excerpt('8'); ?></p></a>
        </div>
        <?php
    }
    ?>

And enjoy! ;) sorry for my bad English..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM