首页 > 解决方案 > 收到一定数量的视图后如何在 WordPress 上隐藏内容

问题描述

在帖子或页面收到我使用 WordPress 中的简码设置的一定数量的视图后,如何隐藏内容?

假设我发了一个帖子。我在简码中附上了一些内容。我将内容设置为仅显示 500 次观看。然后,一旦帖子的浏览量达到 500 次,内容就会从帖子或页面中消失。

我尝试了很多其他插件,但找不到任何解决方案。wp-limit-post-views 插件也没有解决我的问题。我需要这方面的帮助。

标签: wordpresswordpress-shortcode

解决方案


你可以尝试这样的事情:

function hide_contents_function($atts, $content) {
    $attributes = shortcode_atts(
        array(
            'count' => 500
        ),
        $atts
    );

    // Get the max counts for the current post from the DB.
    // You could use either an options if the counter is global, or the post meta.
    // For this example I am using options, but it's up to you the implementation
    $total_count = get_option('total_count', 0);

    // Alternative way using post meta to get the counter per page/post
    $total_count = get_post_meta(get_the_ID(), 'post_view_count', true);
    if ( ! $total_count ) {
        $total_count = 0;
    }

    // If the count loaded from the DB is bigger than the count 
    // property value then return nothing.
    if ( $total_count > (int)$attributes['count'] ) {
        return '';
    }

    return do_shortcode($content);
}
add_shortcode('hide_contents', 'hide_contents_function');

上面的代码将注册一个短代码,该代码接受一个属性,允许您在隐藏内容之前控制想要拥有的视图数量。

在此示例中,我使用了选项表中的单个值,但您可以随意使用任何您喜欢的方法来计算单个帖子的总浏览量。

要使用这个短代码,您可以执行以下操作:

[hide_contents count="345"]I will be hidden after 345 views.[/hide_contents]

请注意,如果您安装了任何缓存系统,如果页面被缓存,您的内容将不会被隐藏!那不是短代码的问题,而是缓存的问题。

最后,记得在每次帖子刷新时更新视图的计数器 :)


推荐阅读