2017-01-07 8 views
1

私はいくつかの投稿IDを持っており、これらの投稿の同じURLからのおすすめ画像を設定したいと思います。ここで特集映像をURLからプログラムで設定するには?

は私の追加のポストコードです:

$catid = get_cat_ID("XX Cat"); 

$my_post = array(); 
$my_post['post_title'] = $title; 
$my_post['post_content'] = $description; 
$my_post['post_status'] = 'publish'; 
$my_post['post_author'] = 1; 
$my_post['post_category'] = array($catid); 

$post_id = wp_insert_post($my_post); 

例:example.com/image.png

私はこれをどのように操作を行うことができます= 1 post_idのは、私がする機能を備えた画像を設定したいですか?

答えて

3

イメージは、メディアライブラリに入っているときに、特集サムネイルとして設定できます。メディアライブラリにイメージを追加するには、イメージをサーバーにアップロードする必要があります。

すると、このコードを試してみてください。

// Add Featured Image to Post 
    $image_url  = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here 
    $image_name  = 'wp-header-logo.png'; 
    $upload_dir  = wp_upload_dir(); // Set upload folder 
    $image_data  = file_get_contents($image_url); // Get image data 
    $unique_file_name = wp_unique_filename($upload_dir['path'], $image_name); // Generate unique name 
    $filename   = basename($unique_file_name); // 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); 

REFのURL:あなたの条件として変更http://www.wpexplorer.com/wordpress-featured-image-url/

: その目的のためにwordpressの標準を無視し、カスタムフォルダにあなたのすべてのポスト単一の画像をアップロードし、この画像を追加しますあなたがあなたのテーマに投稿を表示するときは、post idの助けを借りてあなたのimgを使用してください。 デモコード: あなたのテーマのページに画像を取得するための画像

<?php 
    update_post_meta ( 7, 'imgkey', 'www.url.path');//7 is post id 
?> 

を設定するため、あなたがカスタムメタフィールドは、この記事を読んでワードプレスのポストで新しく追加された場合、それを

<?php 
$img_value = get_post_meta(get_the_ID(), 'imgkey', true); 
?> 
<img src="<?php echo $img_value?>"> 

注意を表示したいです https://codex.wordpress.org/Custom_Fields
またはカスタムフィールドに関する
非公式記事:https://premium.wpmudev.org/blog/creating-custom-fields-manually

+0

1枚の画像しか使用しません。しかし、このコードは複数の画像を1つ以上追加しています...また、異なるサイズの画像を追加したくありません。私は元のサイズだけでなければならないイメージをアップロードしたいと思います... –

+0

私は私の答えを更新しています –

関連する問題