WordPress文章按浏览量排序的方法

追格官方小助手/ 2022年03月30日/ WordPress/ 浏览 1937

今天追格小程序小编给大家分享WordPress文章按浏览量排序的方法,适用于调用分类的热门文章,本文仅适合具备一定编程基础的人进行二次开发。


1、展示浏览量的示例代码

在WordPress主题的functions.php文件至下方的“?>”前,加入以下PHP代码即可。


function themetuts_record_visitors(){ if (is_singular()) {
 global $post; $post_ID = $post->ID; if($post_ID) { $post_views = (int)get_post_meta($post_ID, 'views', true); if(!update_post_meta($post_ID, 'views', ($post_views+1))) { add_post_meta($post_ID, 'views', 1, true); } } } } add_action('wp_head', 'themetuts_record_visitors'); function themetuts_the_view($before = '', $after = '', $echo = 1) { global $post; $post_ID = $post->ID; $views = (int)get_post_meta($post_ID, 'views', true); if ($echo) echo $before, number_format($views), $after;
 else return $views; }


2、文章页面调用本标签


<?php themetuts_the_view(); ?>


3、按浏览量排序示例代码


<?php$args=array('meta_key' => 'views','orderby' => 'meta_value','order' => 'date');query_posts($args);while ( have_posts() ) : the_post();?>								
    <li>
        <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
            <?php if(has_post_thumbnail()) {the_post_thumbnail('post');} else { ?><img src="<?php echo get_template_directory_uri();?>/images/thumbnail/<?php echo rand(1,6);?>.png" alt="<?php the_title(); ?>" /><? } ?>
            <span class="itemtit"><?php the_title(); ?></span>
            <span class="itempoint clr">
                <span class="price"><?php the_field('price'); ?></span>
                <span class="hots"><span class="fa fa-sun-o"></span><?php themetuts_the_view(); ?></span>
            </span>
        </a>
    </li><?php endwhile;wp_reset_query();?>


发表评论

暂无评论,抢个沙发...

客服 工单