【问题标题】:Trying to Create a Popular Posts Page on WordPress with PHP尝试使用 PHP 在 WordPress 上创建热门帖子页面
【发布时间】:2012-06-26 03:36:44
【问题描述】:

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

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

我对 PHP 很陌生,所以如果有人能就如何调整 Wordpress popular posts without using plugins 代码以显示五个帖子并去掉不正确的 0 Views 位,我将不胜感激。

谢谢!

【问题讨论】:

    标签: php wordpress wordpress-theming


    【解决方案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());
    

    那么问题二,你不能用操作符查询帖子,所以你不能只查询浏览量最高的五个帖子,所以你可能必须查询所有帖子,将视图自定义字段和帖子ID存储在一个数组,然后对数组进行排序(使用 php 的 sort 函数)。现在你得到了每个帖子的 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' 选择器,然后您可以随意循环它们。

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

    【讨论】:

    • 非常感谢!!我将在接下来的几天内努力实现这一点。 :)
    猜你喜欢
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多