【问题标题】:PHP Advanced Custom Field Repeater FieldPHP 高级自定义字段中继器字段
【发布时间】:2013-04-23 21:52:05
【问题描述】:

我知道如何使用 echo 来做到这一点,在这种格式中很难找到一些帮助:)

 <?php

    $user_roles = $current_user->roles;
    $user_role = array_shift($user_roles);


        if(get_field('doc-$user_role')): ?>

        <ul>
          <?php while(has_sub_field('doc-$user_role')): ?>

        <li>
         <h3><?php the_sub_field('doc_name'); ?></h3>
           <p><?php the_sub_field('doc_description'); ?></p>
            <a href="<?php the_sub_field('download_doc'); ?>" target="_blank"><img src="<?php bloginfo('template_directory'); ?>/images/download.png" alt="download_button"></a>

        </li>
    <?php endwhile; ?>
        </ul>

    <?php endif; ?>

【问题讨论】:

  • 我不明白你的问题。你能详细说明一下吗?
  • this is wrong if(get_field('doc-$user_role')): ?> 应该怎么写?我有一个用户角色名称,想在它前面添加文档。

标签: php wordpress custom-fields


【解决方案1】:

"" 和 '' 字面量之间存在差异。当您将变量放入“”时,它将被 php 解析,因为它是字符串。当您将其放入 '' 时,它被视为 char 数组并且变量不会被解析,这就是为什么您需要使用 "" 文字或 sprintf() 或者您可以使用点运算符连接两个字符串。

所以你的选择是:

  if(get_field("doc-$user_role"))
  if(get_field('doc-'.$user_role))
  if(get_field("doc-".$user_role))
  if(get_field(sprintf("doc-%s", $user_role)))

sprintf 在您有长字符串并且不想乱写代码时很有用。

http://php.net/manual/en/function.sprintf.php

这里你有完整的解释字符串在 PHP 中是如何工作的

http://php.net/manual/en/language.types.string.php

【讨论】:

    【解决方案2】:

    使用concatenation operator:

    if(get_field('doc-' . $user_role))
    

    【讨论】:

      【解决方案3】:
          if(get_field("doc-$user_role")): ?>
      

      会是正确的,因为在被单引号括起来的字符串中,变量是 not 解析的。仅在带双引号的字符串中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-15
        • 2013-07-14
        • 2015-01-21
        • 2015-12-28
        • 2016-02-01
        • 2013-07-28
        • 2020-05-02
        • 2017-12-16
        相关资源
        最近更新 更多