LoginSignup
11
14

More than 5 years have passed since last update.

WordPressでアイキャッチ画像の登録をphpから行う

Last updated at Posted at 2016-02-02

いつも忘れてしまうので備忘録。
WordPressのアイキャッチ画像をプログラムで登録したい場合のコード。
サーバ上のどこかにアイキャッチにしたい画像がすでにある前提です。

<手順>
1. 画像のメタ情報を取得
2. アタッチメント登録
3. 該当のポストにアイキャッチとして登録

サンプルコード

functions.php
$upload_path = "upload_dir/path/filename.png"; // アイキャッチ画像のサーバ上のファイルパスを指定(※URLではない)

// ファイルメタ情報登録
$meta = getimagesize($upload_path);
$attachment = array(
  'post_mime_type' => image_type_to_mime_type($meta[2]),
  'post_title' => preg_replace('/\.[^.]+$/', '', $upload_path),
  'post_content' => '',
  'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $upload_path, $post_id );

if($attach_id) {
  require_once(ABSPATH . "wp-admin" . '/includes/image.php'); // これが必要
  $attach_data = wp_generate_attachment_metadata( $attach_id, $upload_path );
  wp_update_attachment_metadata( $attach_id,  $attach_data );

  // ファイル添付が完了したらアイキャッチとしてpost_metaを更新
  update_post_meta($post_id, '_thumbnail_id', $attach_id);
}
11
14
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
14