首页 > 解决方案 > 如果高级自定义字段中的值满足特定条件,则显示额外文本

问题描述

我在自定义 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 或更大,有什么想法可以向此输出添加一些文本吗?

标签: phpwordpressadvanced-custom-fields

解决方案


假设 in 的值movie_rating_john只是一个没有其他文本或字符的数字,那么您可以执行以下操作:

  1. 使用get_field而不是将the_field其保存在变量中
  2. 用于intval将其转换为整数
  3. 检查值以决定是否添加额外的文本

把它们放在一起,你会得到下面的代码。换成<?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;
}
?>

推荐阅读