首页 > 解决方案 > 需要进行哪些编辑,以便 Jetpack 热门帖子显示所有时间的热门帖子,而不仅仅是过去 2 天?

问题描述

我想向我的网站添加一个小部件,以显示有史以来浏览次数最多的帖子。到目前为止,我尝试过的每个插件似乎都使用自己的数据库,在安装时进行初始化,而不是使用内部统计信息。Jetpack 似乎保留了这些统计数据,但它的热门帖子小部件仅提供最近 1-2 天的数据,并且没有针对较长时间段的内置选项。

我尝试破解top-posts.php小部件,但成功有限。这是我文件中的相关部分:

            /**
             * Filter the number of days used to calculate Top Posts for the Top Posts widget.
             * We do not recommend accessing more than 10 days of results at one.
             * When more than 10 days of results are accessed at once, results should be cached via the WordPress transients API.
             * Querying for -1 days will give results for an infinite number of days.
             *
             * @module widgets
             *
             * @since 3.9.3
             *
             * @param int 2 Number of days. Default is 2.
             * @param array $args The widget arguments.
             */
            $days = (int) apply_filters( 'jetpack_top_posts_days', 999999, $args );

            /** Handling situations where the number of days makes no sense - allows for unlimited days where $days = -1 */
            if ( 0 == $days || false == $days ) {
                    $days = 2;
            }

            $post_view_posts = stats_get_from_restapi( array(), 'top-posts?max=11&summarize=1&num=' . absint( $days ) );

如果我将默认值更改$days为 10,则统计信息将在 10 天内正确计算。但实际显示的帖子数量与要求的不同。使用$days=10,当您请求其中的 10 个时,只会显示前 6 个帖子。如果我设置$days为像 99999 这样的大数字,那么它报告没有帖子显示如果是 4 或更少,如果是 10 $count,则只有两个帖子显示。$count

我还应该补充一点,正如所写的那样,您实际上无法设置$days=-1并使其工作,因为$post_view_posts使用绝对值。当然,摆脱它很容易,absint但这并不能解决这个返回错误数量的帖子的奇怪问题......

那么......有谁知道正确的编辑来完成这个?

标签: wordpressjetpack

解决方案


而不是试图破解只会在更新时被替换的小部件,您可以使用过滤器。请注意,这-1就是您要返回的无限天数。

function jetpackme_top_posts_timeframe() {
return '-1';
}
add_filter( 'jetpack_top_posts_days', 'jetpackme_top_posts_timeframe' );

把它放在你的子主题的functions.php中。

参考:https ://jetpack.com/2016/01/12/hooks-customize-top-posts-pages-widget/


推荐阅读