php - 如果高级自定义字段中的值满足特定条件,则显示额外文本
问题描述
我在自定义 Wordpress 模板中使用高级自定义字段来为评论网站提供支持。我当前的代码让我可以显示我需要的内容,但现在如果任何评论在 100 分中获得 90 分或更高分,我想显示一些额外的文本。
我使用以下代码获取所有帖子及其评分:
<?php
$posts = get_posts(array(
'posts_per_page'=> 12,
'paged' => $paged,
'post_type'=> 'movie',
'meta_key' => 'movie_rating_john',
'orderby' => 'meta_value',
'order' => 'DESC'
));
if( $posts ): ?>
满分 100 的分数保存在movie_rating_john
键中,我可以这样输出:
<?php the_field('movie_rating_john'); ?>
如果键的值为 90 或更大,有什么想法可以向此输出添加一些文本吗?
解决方案
假设 in 的值movie_rating_john
只是一个没有其他文本或字符的数字,那么您可以执行以下操作:
- 使用
get_field
而不是将the_field
其保存在变量中 - 用于
intval
将其转换为整数 - 检查值以决定是否添加额外的文本
把它们放在一起,你会得到下面的代码。换成<?php the_field('movie_rating_john'); ?>
这个。
<?php
$rating_str = get_field('movie_rating_john'); // 1. Save value as variable
$rating_num = intval($rating_str); // 2. Convert to integer
if ($rating_num >= 90){ // 3. Check value
// if the value is greater than or equal to 90, echo the number and your text
echo $rating_num." this is your extra text here";
}
else{
// if the value is less than 90, just echo the number
echo $rating_num;
}
?>
推荐阅读
- python - 我的 HoloViews 散点图上未显示垂直线,因为它超出了我的散点图的 x 范围
- ubuntu - UFW 规则被忽略
- php - 导航栏图标应该在某些页面上改变颜色
- python - pyistaller - OSError:无法加载 AutoItX
- bash - 在makefile中,当我在bash函数中使用if语句时会抛出错误
- java - 使 Json 成为 Angular 对象
- java - 如何以字符串 Base64 格式存储 PDF 内容
- spyder - PyMC3:Spyder 中的 RuntimeError
- amazon-web-services - Amazon AppSync 是否支持 Amazon QLDB?
- javascript - JavaScript 正则表达式包含,但不完全匹配