获取wp_INSERT_POST()后的特色图片URL

时间:2016-03-02 作者:Naderjlyr

我想获取一幅特色图片的url。

我创建了一个函数wp_insert_post 发布数据并为其设置特色图像。除了显示特色图片的url外,一切正常。

这是我的代码:

$newpostname = $movie[\'title\'];

global $wpdb;

$id_ofpost_name     = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_name = \'$newpostname\'" );
$id_ofpost_title    = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = \'$newpostname\'" );

if( $id_ofpost_name || $id_ofpost_title ) { echo \'post Exist\'; } 
else {
    // Register Post Data
    $post                   = array();
    $post[\'post_status\']    = \'publish\';
    $post[\'post_type\']      = \'post\';               // can be a CPT too
    $post[\'post_title\']     = $newpostname;
    $post[\'post_content\']   = \'\';
    $post[\'post_author\']    = 1;

    // Create Post
    $post_id = wp_insert_post( $post );

    // Add Featured Image to Post
    $image_url  = $movie[\'urlPoster\'];
    $upload_dir = wp_upload_dir();                  // Set upload folder
    $image_data = file_get_contents( $image_url );  // Get image data
    $filename   = basename( $image_url );           // Create image file name

    // Check folder permission and define file location
    if( wp_mkdir_p( $upload_dir[\'path\'] ) ) {
        $file = $upload_dir[\'path\'] . \'/\' . $filename;
    } else {
        $file = $upload_dir[\'basedir\'] . \'/\' . $filename;
    }

    // Create the image  file on the server
    file_put_contents( $file, $image_data );

    // Check image file type
    $wp_filetype = wp_check_filetype( $filename, null );

    // Set attachment data
    $attachment = array(
        \'post_mime_type\' => $wp_filetype[\'type\'],
        \'post_title\'     => sanitize_file_name( $filename ),
        \'post_content\'   => \'\',
        \'post_status\'    => \'inherit\'
    );

    // Create the attachment
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

    // Include image.php
    require_once(ABSPATH . \'wp-admin/includes/image.php\');

    // Define attachment metadata
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

    // Assign metadata to attachment
    wp_update_attachment_metadata( $attach_id, $attach_data );

    // And finally assign featured image to post
    set_post_thumbnail( $post_id, $attach_id );
}
插入后的效果非常好!问题是我想在上传后获得特色图片的url。我该怎么做?

1 个回复
SO网友:Howdy_McGee

你的身份是$attach_id 因此,您可以使用以下函数wp_get_attachment_url() 你可以通过的地方$attach_id 并获取返回的url:

$featured_url = wp_get_attachment_url( $attach_id );
或者,如果您需要更多信息,如宽度、高度等,您可以使用以下功能wp_get_attachment_image_src()wp_get_attachment_metadata().