[WordPress]プラグインから記事を投稿する

プラグイン「WP Rss Poster」はRSSを取得し、記事として投稿します。
これと同じようにプラグイン内に記事があり、それを投稿する仕組みです。
(プラグインの作り方とか、記事一覧とかは省きます。)

■記事の投稿

プラグインから記事を投稿するには、「wp_insert_post」を使用して記事をDBに追加します。

$post = array(
  'post_status' => 'publish',
  'post_title' => 'タイトル',
  'post_content' => '本文',
  'post_category' =>  array('カテゴリーID', 'カテゴリーID')
);
$post_id = wp_insert_post( $post );

 

■カスタムフィールド

カスタムフィールドは記事投稿後にpost_idに対してpost_metaで追加します。
WP insert post PHP function and Custom Fields

public function __update_post_meta($post_id, $field_name, $value = '') {
    if (empty($value) OR !$value) {
        delete_post_meta($post_id, $field_name);
    } elseif (!get_post_meta($post_id, $field_name)) {
        add_post_meta($post_id, $field_name, $value);
    } else {
        update_post_meta($post_id, $field_name, $value);
    }
}
$my_post = array(
    'post_title' => $_SESSION['booking-form-title'],
    'post_date' => $_SESSION['cal_startdate'],
    'post_content' => 'This is my post.',
    'post_status' => 'publish',
    'post_type' => 'booking',
);
$the_post_id = wp_insert_post( $my_post );

__update_post_meta( $the_post_id, 'my-custom-field', 'my_custom_field_value' );

 

■アイキャッチ

カスタムフィールドと同様に記事投稿後にpost_idに追加する
Get and resize Thumbnails with images taken from custom fields

//$value is the filename

$save_path = "folder/";
$file = realpath($save_path).'/'.$value;
$wp_filetype = wp_check_filetype(basename($file), null );
// Construct the attachment array
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'guid' => $file,
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($post_name)),
    'post_content' => '',
    'post_parent' => $post_id,
    'post_status' => 'inherit'
);

// Save the data
$id = wp_insert_attachment($attachment, $file, $post_id);
$attach_data = wp_generate_attachment_metadata( $id, $file );
wp_update_attachment_metadata( $id, $attach_data );
set_post_thumbnail( $post_id, $id );

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)