如果高级自定义字段中的值满足特定条件,则显示额外文本
Display extra text if the value in Advanced Custom Fields meets specific criteria
我在自定义 Wordpress 模板中使用高级自定义字段来支持评论网站。
我当前的代码允许我显示我需要的内容,但现在我想在任何评论获得 90 分或更高分(满分 100 分)时显示一些额外的文本。
我使用以下代码获取所有帖子及其评分:
<?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 或更大,我可以如何向此输出添加一些文本?
假设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;
}
?>
我在自定义 Wordpress 模板中使用高级自定义字段来支持评论网站。 我当前的代码允许我显示我需要的内容,但现在我想在任何评论获得 90 分或更高分(满分 100 分)时显示一些额外的文本。
我使用以下代码获取所有帖子及其评分:
<?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 或更大,我可以如何向此输出添加一些文本?
假设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;
}
?>