2016-04-22 77 views
1

我正在刮一個網站並將數據放入我的WP網站。如何鏈接到我的WP文章中的外部圖像

這些帖子中有很多圖片。

我希望在將抓取的數據導入我的WP站點時,我想直接從該外部URL將圖像鏈接到我的站點,而不是將圖像下載到我的服務器。

我在語法上將抓取的數據導入到我的網站。

以下是添加圖像

// for image 
    $ins_q = "INSERT INTO wpxw_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, " 
      . "comment_status, ping_status," 
      . "post_password, post_name, to_ping, pinged, post_modified,post_modified_gmt, post_content_filtered,post_parent," 
      . "guid,menu_order,post_type," 
      . "post_mime_type,comment_count) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; 

    $sth = $conn->prepare($ins_q); 
    if (!$sth->execute(array(
       $post_author, $date, $date, "", sanitize_title_with_dashes($image_name), "", "inherit", "open", "closed", '', 
       str_replace(".", "-", $image_name), '', '', $date, $date, '', $post_id, 
       "http://photos2.zillowstatic.com/p_f/ISdc6hruhctopo0000000000.jpg" 

       , 0, "attachment", "image/jpeg", 0 
      ))) { 
     echo "<h1>Error</h1>"; 
     print_r($sth->errorInfo()); 
     exit(); 
    } 

}

我的問題是增加外部鏈接到圖像時,圖像不顯示在我的崗位的那部分。我如何顯示來自外部資源的圖像?

+1

相反,您可以使用wordpress函數wp_insert_attachment。 https://codex.wordpress.org/Function_Reference/wp_insert_attachment – user5200704

回答

1
// Add Featured Image to Post 
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here 
$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); 
+0

這是什麼?它不會將圖像保存到我的WP網站? – Umair

相關問題