douxidang9092
2018-08-16 19:52 阅读 55
已采纳

“wp_get_attachment_url”在functions.php中不起作用

This works just fine in any other post:

$vid_att = get_attached_media('video',$post_id); // Check if a video is attached
// print_r($vid_att);
if ($vid_att) {
$vid_att_url = wp_get_attachment_url($vid_att->ID);
echo $vid_att_url;
}

HOWEVER

if I use this within my functions.php file it will return the full array (print_r($vid_att);) but will not return the ID when requested!

If I insert the attachment ID manually it works:

$vid_att_url = wp_get_attachment_url('138');

What can it be? I've tried converting ID to Integer and other stuff but cannot get it to work. Also ne errors given.

The array it returns looks like this:

Array ( [138] => WP_Post Object ( [ID] => 138 [post_author] => 1 [post_date] => 2018-08-14 16:21:42 [post_date_gmt] => 2018-08-14 16:21:42 [post_content] => [post_title] => SampleVideo_1280x720_1mb [post_excerpt] => [post_status] => inherit [comment_status] => open [ping_status] => closed [post_password] => [post_name] => samplevideo_1280x720_1mb [to_ping] => [pinged] => [post_modified] => 2018-08-14 16:21:42 [post_modified_gmt] => 2018-08-14 16:21:42 [post_content_filtered] => [post_parent] => 113 [guid] => http://flockstock/wp-content/uploads/edd/2018/08/SampleVideo_1280x720_1mb.mp4 [menu_order] => 0 [post_type] => attachment [post_mime_type] => video/mp4 [comment_count] => 0 [filter] => raw ) )
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    duankeng2026 duankeng2026 2018-08-17 13:44

    Conclusion:

    $vid_att = get_attached_media('video',$post_id); // Check if a video is attached
    
        if ($vid_att) {
    
                $vid_att_arr = array_values($vid_att);
                $vid_att_ID = $vid_att_arr[0]->ID;
                $vid_att_url = wp_get_attachment_url($vid_att_ID);
                // echo $vid_att_url;
            }else{
                echo 'No Video uploaded!';
            }
    
    点赞 评论 复制链接分享
  • douxu3315 douxu3315 2018-08-16 23:52

    Try to declare the super variable before like that :

    global $post;
    echo $post->ID;
    
    点赞 评论 复制链接分享
  • duanmuybrtg1231 duanmuybrtg1231 2018-08-17 08:35

    Thanks @wkille for pointing to this post where the answer lies: Get attachment URL

    reindex the array before using it:

    $vid_att = array_values($vid_att);
    echo 'GUID: ' . $vid_att[0]->guid;
    

    Note:

    wp_get_attachment_url($post_id->ID);
    

    still doesn't work within functions.php even if you reindex the array but it does work in posts, anyone know why this is?

    点赞 评论 复制链接分享

相关推荐