微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在带有if语句的数组中获取foreach语句输出以在Wordpress + ACF中用逗号内爆?

如何解决如何在带有if语句的数组中获取foreach语句输出以在Wordpress + ACF中用逗号内爆?

我正在用 wordpress 制作一个艺术家作品集网站。我正在为自定义帖子类型艺术品处理单个页面,其中包含使用 ACF 创建的大量元数据字段。我在显示带有合作者姓名的 ACF 转发器字段的内容时遇到了麻烦,如果有的话,他们为链接到他们个人网站的艺术品做出了贡献(如果他们有的话)。该中继器作为一个元素被克隆到艺术品字段组中。

我已经能够使用下面的代码显示带有和不带有链接的协作者的姓名。所以它会显示“共同创建者:Name1 (with href)Name2 (no href)”。但是逗号不会出现在协作者之间。我认为这是因为我没有正确创建数组。

任何帮助将不胜感激。

<?PHP
while (have_posts()) : the_post();
  // lots more code here
  $artwork_collaborators = get_field('artwork_collaborators'); // get the value of the acf clone field
  if ($artwork_collaborators) : // check if has data ?>
  <dd id="single-artwork-collaborators"><?PHP 
    _e('Co-creators: ','aopa'); // multilanguage label for translation
    foreach ($artwork_collaborators as $artwork_collaborator) : // foreach loop to get all collaborators
      if ($artwork_collaborator['artwork_collaborator_url']) : // check if there is a url for the collaborator
        $array_collaborators = array('<a href="'. $artwork_collaborator['artwork_collaborator_url'] . '" target="_blank">' . $artwork_collaborator['artwork_collaborator_name']  . '</a>'); // create array with URL
      else :
        $array_collaborators = array($artwork_collaborator['artwork_collaborator_name']); // create array without url
      endif;
      
      $collaborator_string = implode(",",$array_collaborators); // implode the array and add commas
      echo $collaborator_string; // echo the collaborators with link or no link separated by commas if there is more than one
    endforeach; ?>
  </dd>
  <?PHP endif;
  // lots more code here 
endwhile?>

解决方法

我最终从一个程序员朋友那里得到了一些关于这个问题的帮助。现在输出是“Co-creators: Name1 (with href),Name2 (no href)”,逗号在正确的位置,链接在需要时就在合适的位置,不需要时不在那里。

主要问题之一是内爆和回声在循环内。这导致他们重复了太多次。

我们还在顶部创建了一个空数组,然后将所有字符串添加到其中。请参阅下面代码中的注释:

www.mysite.com/market/?utm=email&utm_from=email&campaign=13424

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。