尝试使用PHP在WordPress上创建一个受欢迎的帖子页面

时间:2012-06-26 03:36:45

标签: php wordpress wordpress-theming

非常感谢有关以下方面的信息: Wordpress popular posts without using plugins这极大地帮助我为我的WordPress网站整理了我自己的热门帖子页面模板。但是,我认为我需要更改代码以使其表现更好并且不确定该怎么做。

新页面位于http://sassyginger.com/most-popular-posts。它显示了两个帖子(当它应该显示五个时),然后将它们与“零视图”相关联,我知道这是不对的。

我是PHP的新手所以非常感谢任何人都可以帮我解决如何调整Wordpress popular posts without using plugins代码以显示5个帖子并且忽略不正确的0视图位。

谢谢!

1 个答案:

答案 0 :(得分:1)

Wordpress默认情况下不会跟踪帖子上的视图,因此如果您不想使用插件,则需要为包含视图的所有帖子创建自定义字段。然后编写一个获取该值的函数,并添加一个人加载该页面的所有内容。 (假设您将函数放在functions.php中)并从单个模板中调用它并发送postid。

函数可能看起来像这样:

function addPostView($postID) {
$views = 'post_views'; // post_views is the custom field name
$count = get_post_meta($postID, $views, true); // grab the value from that custom field

// Now we need to check that the value we just grabbed isn't blank, if it is we need to set it to 1, since it would be our first view on this post.
if($count==''){
    $count = 0;
    update_post_meta($postID, $views, '1');
}else{
    // else we can just add one to the number.
    $count++;
    update_post_meta($postID, $views, $count);
}
}

在我们的单模板中,我们将函数称为:

addPostView(get_the_ID());

然后问题二,您无法使用运算符查询帖子,因此您无法查询具有最高视图的五个帖子,因此您可能必须查询所有帖子,存储视图custom-field和post id in一个数组,然后对数组进行排序(使用php的排序函数)。现在,您获得了每个帖子ID,并在数组中发布视图。因此,取前五个(或最后一个取决于你如何排序),你得到了五个具有最多观看次数的postID。

//ordinary wp_query
$i = 0; // keeping track of our array
//while(post-> etc....
    global $post;
    $views = get_post_meta($post->ID, 'post_views', true); // Grab our value
    /* You could also use an object here */
    $postArray[$i][0] = $views; // set it in slot $i of our array
    $postArray[$i][1] = $post->ID; // and also set the postID in the same slot

    $i++;
//endwhile;

对数组进行排序:

 rsort($postArray);
 $postArray = array_slice( $postArray, 0, 5 ); // grab only the first 5 values, which will be the ones with highest views.

现在您需要进行第二次查询,只需查询这些ID(使用'post__in'选择器,然后您可以根据需要将它们循环出来。

请注意我没有尝试过这段代码,但过去我做过类似的事情。它可能不是最好的解决方案,但它可以完成工作。通过所有帖子查询(如果你有很多帖子),只能获取五个左右的帖子,不能是好的做法:)