[wordpress] プログラムで記事投稿+アイキャッチ画像登録
wordpressにプログラムで記事投稿+アイキャッチ画像登録するには以下のコードを実装
require('./wp-blog-header.php'); //wp-blog-header.phpと同じフォルダに配置している場合 $artTitle = '記事のタイトル' ; $html = '記事の本文' ; $url = 'アイキャッチ画像のURL' ; postToBlog($artTitle,$html,$url); function postToBlog($artTitle,$html,$url){ // 自動投稿をさせるコード $blog_id = 3; //複数サイト運営している場合 switch_to_blog( $blog_id ); //複数サイト運営している場合 $post = array( 'post_author' => 3, // 作成者のユーザー ID。 'post_content' => $html, // 投稿の全文。 'post_status' => 'publish', // 公開ステータス。 'post_title' => $artTitle, // 投稿のタイトル。 'post_category' => array(1,5), // カテゴリーID(配列)。 'tags_input' => array('タグ1′,'タグ2′), // タグの名前(配列)。 ); $postid = wp_insert_post( $post ); ore_add_thumbnail($postid,$url); restore_current_blog(); } //画像URLをpost_idのアイキャッチに登録する function ore_add_thumbnail($posted_id,$url){ //アップロードディレクトリ取得 $wp_upload_dir = wp_upload_dir(); //ファイル名取得 $filename = basename( $url ); //ダウンロード後ファイルパス $filename = $wp_upload_dir['path'] . "/" . $filename; //画像をダウンロード&保存 $image_data = file_get_contents($url); file_put_contents($filename,$image_data); //ファイル属性取得 $wp_filetype = wp_check_filetype($filename, null ); //添付ファイル情報設定 $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . $filename, 'post_mime_type' => $wp_filetype['type'], 'post_title' => $filename, 'post_content' => '', 'post_status' => 'inherit' ); //添付ファイル登録 $attach_id = wp_insert_attachment( $attachment, $filename, $posted_id ); //サムネイル画像作成 require_once( ABSPATH . 'wp-admin/includes/image.php' ); $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); //サムネイルID登録 add_post_meta( $posted_id, "_thumbnail_id" ,$attach_id, true); }