【问题标题】:how to get image url in advanced custom field wordpress post如何在高级自定义字段 wordpress 帖子中获取图像 url
【发布时间】:2016-06-14 21:09:26
【问题描述】:

我创建了一个名为“相册”的自定义帖子类型。我的每个帖子中有 5 个自定义字段。 3 个文本字段、1 个图像字段和 1 个文件上传字段。我在模板页面中正确获取了 3 个文本值。但我无法获取图像和文件上传字段的 url 部分。 这是我的代码:

<?php

$posts = get_posts(array(
'post_type' => 'albums'
));

if($posts)
{
echo '<ul>';

foreach($posts as $post)
{
    echo '<li><a href="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</a></li>';
         the_field('album_category'); echo "<br>";
          the_field('album_name'); echo "<br>";
           the_field('slide_name'); echo "<br>";
            the_field('slide_description'); echo "<br>";
            the_field('audio_file'); echo "<br>";
}

echo '</ul>';
}

?> 

这是我当前的输出

Cuckoo-1
鸟类
Cuckoo
66, , 2668245306_027a56fe50_b, , , image/jpeg, http://localhost/YIB/wordpress/wp-content/uploads/2016/03/2668245306_027a56fe50_b-1.jpg, 1024, 768, 阵列
样品样品样品样品样品样品样品样品
18, , eudynamys-scolopacea, , "eudynamys-scolopacea"., 音频/mpeg, http://localhost/YIB/wordpress/wp-content/uploads/2016/03/eudynamys-scolopacea.mp3

【问题讨论】:

    标签: php wordpress advanced-custom-fields


    【解决方案1】:

    上传到媒体库的图片、视频或文件等媒体的自定义字段以数组的形式保存为元数据。您可以尝试这个简单的函数从自定义字段的元数据中提取 URL 值。此函数在检测到元值中的有效 URL 时遍历数组并返回 URL 元值。

    将此函数添加到您的 functions.php

    function get_post_asset_url($postid, $slug) {
      $meta_array = get_post_meta($postid, $slug, true);
      foreach ($meta_array as $meta) { 
        if (filter_var($meta, FILTER_VALIDATE_URL)){ return $meta; } 
      } 
    }
    

    在您的模板中,在“echo”语句中调用此函数:

    echo get_post_asset_url($post->ID, "your_asset_field_name");
    

    因此,例如在图像字段上:

    <img src="<?php echo get_post_asset_url($post->ID, "image_field_1"); ?>" width="100" height="100">
    

    【讨论】:

      【解决方案2】:

      试试这个。

      图像字段和文件字段返回数组所以

      $image_m =  get_field('slide_description');
      $image_a = get_field('audio_file');
      echo '<pre>';
      print_r($image_m);
      print_r($image_a);
      echo '</pre>';
      

      假设你得到了输出

      array(
       ['name'] => 'test';
       ['url'] => 'http://example.mp3';
      
      )
      

      然后写&lt;?php echo $image_m['url'];?&gt;而不是&lt;?php the_field('audio_file');?&gt;

      【讨论】:

      • 如果我们使用 get_field 而不是 get_the_field,它会起作用
      【解决方案3】:

      试试这个

          <?php
          $imgurl = get_field('slide_image',$post->ID);
      
          if (filter_var($imgurl, FILTER_VALIDATE_URL) === FALSE)
          {
            $imgurl = wp_get_attachment_url($imgurl);
          }
             echo '<img src="' . $imgurl . '" alt="image">';
          ?>
      

      【讨论】:

      • 在删除 if 语句后尝试..您的图像字段是否返回 int 值?
      • 你能把管理员设置中的字段截图发给我吗?
      猜你喜欢
      • 2016-03-24
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2016-06-25
      • 2013-10-06
      • 1970-01-01
      相关资源
      最近更新 更多