0

我有一个脚本,允许我从前端将图像上传到 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 当我有足够的帖子时,我会感谢的。提前致谢。

4

1 回答 1

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;
}

但通常,由于您已经将 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="" />';
}
于 2013-09-06T05:39:16.590 回答