wordpress - 收到一定数量的视图后如何在 WordPress 上隐藏内容
问题描述
在帖子或页面收到我使用 WordPress 中的简码设置的一定数量的视图后,如何隐藏内容?
假设我发了一个帖子。我在简码中附上了一些内容。我将内容设置为仅显示 500 次观看。然后,一旦帖子的浏览量达到 500 次,内容就会从帖子或页面中消失。
我尝试了很多其他插件,但找不到任何解决方案。wp-limit-post-views 插件也没有解决我的问题。我需要这方面的帮助。
解决方案
你可以尝试这样的事情:
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]
请注意,如果您安装了任何缓存系统,如果页面被缓存,您的内容将不会被隐藏!那不是短代码的问题,而是缓存的问题。
最后,记得在每次帖子刷新时更新视图的计数器 :)
推荐阅读
- r - 使用 mlr 库中的 knn 模型进行预测
- python - 如何控制 tkinter 按钮小部件上的图像和文本之间的空间?
- arrays - 从 Kotlin 的数组中打印一个范围内的项目数
- configuration - WebPack:在监视列表中包含非捆绑文件以触发重建
- php - 如果 url 以特定字符串结尾,则 wordpress php 函数到自定义页面
- macos - MacOS AppKit - 如何更改关闭、最小化和最大化按钮“standardWindowButton”的颜色
- database - kusto 命令在突出显示的数据库中创建表
- amp-html - Google Amp lightbox 无法在 Safari 上运行
- javascript - node.js 可以进行多少并发数据库查询?
- c - 在图上制作 BFS 函数以获得最短路径