PHP高级自定义字段中继器字段

时间:2013-04-23 12:42:32

标签: php wordpress custom-fields

我有一个变量,我想添加doc-它所以它会在wordpress中读出doc- $ user_role这样的高级自定义字段。

我知道怎么做回声,发现很难以这种格式提供一些帮助请:)

 <?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; ?>

3 个答案:

答案 0 :(得分:1)

&#34;&#34;之间存在差异。和&#39;&#39;文字。将变量放入&#34;&#34;它会被php解析,因为它是字符串。当你把它放入&#39;&#39;它被视为char数组,而变量将不会被解析,这就是你需要使用&#34;&#34; literal或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

答案 1 :(得分:0)

使用concatenation operator

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

答案 2 :(得分:0)

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

是正确的,因为在单引号变量包围的字符串中解析。仅限带双引号的字符串。

相关问题