【问题标题】:Repeatable custom field display可重复的自定义字段显示
【发布时间】:2013-02-17 08:01:05
【问题描述】:

我已经用一些 PHP 来显示一个可重复的字段,但输出只是显示了 Array

任何想法都将不胜感激:

<?php
$repeatable = get_post_meta( get_the_ID(), 'ecpt_eventdaytime', true);
if( !empty($repeatable )) {
    echo '<img src="/wp-content/uploads/2013/02/Time.gif">';
    echo $repeatable ;
    echo "<br><br>";
}
?> 

【问题讨论】:

  • 如果使用get_post_meta()时“single”参数为真,则表示元数据存储为数组。
  • 使用 print_r($repeatable) 查看(并在此处发布)您从自定义字段中获得的信息。

标签: php wordpress custom-fields


【解决方案1】:

试试这样:

<?php if (have_posts()) :
      while (have_posts()) : the_post(); 
        $repeatable = get_post_meta( get_the_ID(), "ecpt_eventdaytime", true ); 
        echo $repeatable ;
      endwhile;
      endif;
?>

或者,如果您想在循环外显示自定义字段值,只需使用以下代码。问题是,您只需要 ID。

<?php 
    global $wp_query;
    $postid = $wp_query->post->ID;
    echo get_post_meta($postid, 'ecpt_eventdaytime', true);
?>

【讨论】:

  • 感谢@RTB - 不幸的是仍然只显示 ARRAY
  • 如果它仍然是一个数组,为什么不直接:&lt;?php echo $repeatable[0]; ?&gt; 从中获取值?
  • 感谢实时出价!!!我在显示第二个可重复字段时遇到问题...例如下面的代码输出 img 后跟第一个字段,但是无论是否存在第二个可重复字段,都会出现第二个 img:&lt;?php if (have_posts()) : while (have_posts()) : the_post(); $repeatable = get_post_meta( get_the_ID(), "ecpt_eventdaytime", true ); echo '&lt;img src="/wp-content/uploads/2013/02/Time.gif"&gt;'; echo $repeatable[0]; echo "&lt;br&gt;"; endwhile; endif; echo '&lt;img src="/wp-content/uploads/2013/02/Time.gif"&gt;'; echo $repeatable[1]; ?&gt;
  • 查看字段类型:&lt;?php var_dump($repeatable[1]); ?&gt;
【解决方案2】:

因为get_post_meta返回数组需要使用循环

引用wordpress

&lt;?php $meta_values = get_post_meta($post_id, $key, $single); ?&gt;

返回值

  • 如果只设置了 $id,它将返回关联数组中的所有元值。
  • 如果 $single 设置为 false 或留空,该函数将返回一个包含指定键的所有值的数组。
  • 如果 $single 设置为 true,则函数返回指定键的第一个值(不在数组中)

【讨论】:

    【解决方案3】:

    如果ecpt_eventdaytime 是数组,那么:

    <?php
    $repeatable = get_post_meta( get_the_ID(), 'ecpt_eventdaytime', true);
    if( !empty($repeatable )) {
        foreach($repeatable as $value) {
            echo '<img src="/wp-content/uploads/2013/02/Time.gif">';
            echo $value;
            echo "<br><br>";
        }
    }
    ?> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-21
      • 2020-06-25
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      相关资源
      最近更新 更多