获取附件URL而不是ID(Wordpress)

时间:2013-09-06 01:50:58

标签: wordpress

我有一个脚本,允许我从前端上传图像到wordpress。然后我需要它将文件发布到post_meta。现在它工作正常,但我最终得到了附件ID,需要链接到文件。

以下是处理此特定功能的代码。

if ($_FILES) {
    foreach ($_FILES as $k => $v) {
        if ($k != 'poster_has_paid' && $k != 'featured_image') {
            if ($_FILES[$k]) {
                wpo_poster_insert_attachment($k, $post_id, false, $k);
            }
        }
    }
}

这是函数wpo_poster_insert_attachment

function wpo_poster_insert_attachment($file_handler, $post_id, $setthumb = 'false', $post_meta = '') {
    // check to make sure its a successful upload
    if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) {
        __return_false();
    }

    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attach_id = media_handle_upload($file_handler, $post_id);

    if ($setthumb) {
        update_post_meta($post_id, '_thumbnail_id', $attach_id);
    }
    if (!$setthumb && $post_meta != '') {
        update_post_meta($post_id, $post_meta, $attach_id);
    }

    return $attach_id;

同样,它正在使用attach_id更新字段,我希望它能更新attach_url

PS当我有足够的帖子时,我会表示感谢。提前谢谢。

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效

function wpo_poster_insert_attachment($file_handler,$post_id,$setthumb='false', $post_meta = '') {
    // check to make sure its a successful upload
    if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attach_id = media_handle_upload( $file_handler, $post_id );

    if ($setthumb) {
        update_post_meta($post_id,'_thumbnail_id',$attach_id);

        // Get the attachment/thumbnail source, and add it to the post meta as well.
        $src = wp_get_attachment_image_src($thumbnail_id, 'full');
        update_post_meta($post_id,'_thumbnail_src', @$src[0]);
    }

    if(!$setthumb && $post_meta!=''){
        update_post_meta($post_id, $post_meta, $attach_id);
    }

    return $attach_id;
}

但通常情况下,由于您已经在post meta中存储了thumbnail_id,因此您可能希望在运行时提取附件源:

if($thumbnail_id = get_post_meta($post->ID, '_thumbnail_id', true)) {
    $attachment_size = 'full';
    $src = wp_get_attachment_image_src($thumbnail_id, $attachment_size);
    if(!$src) {
            $src = array('http://mysite.com/path/to/default-image.png', 640, 480);
    }
    echo '<img src="'.esc_url($src[0]).'" alt="" />';
}