我希望显示符合某些要求的帖子。首先也是最重要的是,这个想法是向访问者展示浏览量最大的帖子。我实现了with some help. 因此,我使用下面的PHP实现了这一点。我为自己工作,这很好。现在我想添加一个约束,即:只有带有缩略图的帖子才有资格循环,但如果没有缩略图,你不能跳过一篇帖子,而只是在实际输出中得到较少的帖子:我总共需要四篇帖子!因此,理想情况下,我希望有一种方法将一个表示“has thumbnail”的参数传递给WP\\u查询。但是,我还需要已经存在的meta\\u键。我如何保留该元密钥,并使用另一个:我发现here 您可以添加\'key\' => \'_thumbnail_id\'
, 但我不确定如何将多个键添加到此查询中。
请记住,我确实需要使用orderby
, 按大多数视图的顺序排列帖子。
为了完整起见,我将发布整个片段,并牢记彼得·古森的答案。我原以为“30天”不会有什么不同,但现在我意识到可能会有不同。post_date_selection
是中的函数functions.php
这将帖子限制在最后30天内。我是从here.
<?php if (is_home()) : ?>
<section class="featured-posts clear">
<?php // restrict loop to 30 last days, see functions.php
add_filter(\'posts_where\', \'post_date_selection\');
global $query_string;
query_posts($query_string);
?>
<?php
$args = array(
\'order\' => \'DESC\',
\'posts_per_page\' => 4,
\'meta_key\' => \'post_views_count\',
\'orderby\' => \'meta_value_num\',
\'meta_query\' => array(
\'relation\' => \'AND\',
array(
\'key\' => \'post_views_count\',
\'compare\' => \'EXISTS\'
),
array(
\'key\' => \'_thumbnail_id\',
\'compare\' => \'EXISTS\'
),
),
);
$popularPosts = new WP_Query($args);
$counter = 1;
?>
<?php while ($popularPosts->have_posts() ) : $popularPosts->the_post(); ?>
<article class="box-<?php echo $counter++; ?>">
<a href=" <?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?><span><?php the_title(); ?></span></a>
</article>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</section>
<?php endif; // is_home ?>
<?php remove_filter(\'posts_where\', \'post_date_selection\'); // remove restriction from loop ?>
函数中最重要的函数。php:/*
* Getting and setting post count
*/
// Set post count
function set_post_views($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);
}
}
// To keep the count accurate, lets get rid of prefetching
remove_action(\'wp_head\', \'adjacent_posts_rel_link_wp_head\', 10, 0);
// Update post count
function track_post_views ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
set_post_views($post_id);
}
add_action( \'wp_head\', \'track_post_views\');
// Only 30 last days, needs in content
function post_date_selection ($when = \'\') {
$when .= " AND post_date > \'" . date(\'Y-m-d\', strtotime(\'-30 days\')) . "\'";
return $when;
}