按WordPress Dashboard Widget的浏览次数对帖子进行排序



我环顾四周,不幸的是,我找不到任何可以帮助我在仪表板小部件中对浏览量最大的帖子进行排序的东西。我可以显示这些帖子以及它们被浏览的次数,但看起来它是根据最近的帖子而不是浏览的次数进行拉取和排序的。

下面是代码。有人能帮我吗?

// Adds view counter
function getCoupontViews($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 "Used 0 Times";
    }
    return 'Used ' .$count. ' Times';
}
// Displays the view counter
function setCouponViews($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);
    }
}       
function clipit_views_db() {
?>
    <ol>
        <?php
        global $post;
        $args = array( 
            'numberposts' => 5,
            'post_type' => 'coupon'
        );      
        $myposts = get_posts( $args );
        foreach( $myposts as $post ) : setup_postdata($post); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php echo getCoupontViews(get_the_ID()); ?> </li>
        <?php endforeach; ?>
    </ol>
<?php
}
function add_clipit_views_db() {
    wp_add_dashboard_widget( 'clipit_views_db', __( 'Recent ClipIt Views' ), 'clipit_views_db' );
}
add_action('wp_dashboard_setup', 'add_clipit_views_db' );

看起来我能够通过向get_posts()添加额外信息来解决这个问题

function clipit_views_db() {
?>
    <ol>
        <?php
        global $post;
        $args = array( 
            'meta_key' => 'post_views_count',
            'numberposts' => 5,
            'orderby' => 'meta_value_num',
            'order' => 'DESC',
            'post_type' => 'coupon'
        );          
        $myposts = get_posts( $args );
        foreach( $myposts as $post ) : setup_postdata($post); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php echo getCoupontViews(get_the_ID()); ?> </li>
        <?php endforeach; ?>
    </ol>
<?php
}
function add_clipit_views_db() {
    wp_add_dashboard_widget( 'clipit_views_db', __( 'Recent ClipIt Views' ), 'clipit_views_db' );
}
add_action('wp_dashboard_setup', 'add_clipit_views_db' );   

最新更新