我想在我的网站上创建一个热门的帖子部分,以显示过去一周最热门的5个帖子。
热门帖子的功能
function shapeSpace_popular_posts($post_id) {
$count_key = 'popular_posts';
$count = get_post_meta($post_id, $count_key, true);
if ($count < 1) {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
} else {
$count++;
update_post_meta($post_id, $count_key, $count);
}
}
function shapeSpace_track_posts($post_id) {
if (!is_single()) return;
if (empty($post_id)) {
global $post;
$post_id = $post->ID;
}
shapeSpace_popular_posts($post_id);
}
add_action('wp_head', 'shapeSpace_track_posts');
热门帖子的循环
<?php $popular = new WP_Query(array(
'posts_per_page'=>5,
'date_query' => array(
//set date ranges with strings!
'after' => '1 week ago',
'before' => 'today',
//allow exact matches to be returned
'inclusive' => true,
),
'meta_key'=>'popular_posts',
'orderby'=>'meta_value_num',
'order'=>'DESC'));
while ($popular->have_posts()) : $popular->the_post(); ?>
<h5 class="section_category">
<?php the_category(', ') ?>
</h5>
<div class="trending_title">
<?php the_title( sprintf( '<h4><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h4>' ); ?>
</div>
<h5 class="section_author">
By <?php coauthors_posts_links(); ?>
</h5>
<div class="border-bottom"></div>
<?php endwhile; wp_reset_postdata(); ?>
如果你能提供帮助,我会很高兴。
谢谢,
答案 0 :(得分:0)
使用“query_posts”而不是“WP_Query”
<?php
$args = array(
'post_type' => 'post',
'showposts' => 5,
'date_query' => array(
//set date ranges with strings!
'after' => '1 week ago',
'before' => 'today',
//allow exact matches to be returned
'inclusive' => true,
),
'meta_key' => 'popular_posts',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
query_posts($args);
//query_posts('post_type=post&showposts=5&meta_key=popular_posts&orderby=meta_value_num&order=DESC');
if (have_posts()) :
?>
<?php
while (have_posts()) : the_post();
?>
<h5 class="section_category">
<?php the_category(', ') ?>
</h5>
<div class="trending_title">
<?php the_title( sprintf( '<h4><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h4>' ); ?>
</div>
<h5 class="section_author">
By <?php coauthors_posts_links(); ?>
</h5>
<div class="border-bottom"></div>
<?php
endwhile;
?>
<?php
endif;
wp_reset_query();
?>