0
0

More than 3 years have passed since last update.

Woocommerceにプロダクトをphpから複数画像付きで追加する

Last updated at Posted at 2020-07-24

はじめに

  • wordpressフォルダに配置されることを想定しています。位置が変わる場合はrequire_onceのパスを変更してください。
  • POSTでタイトルはtitle,説明はExplanation,画像(複数)はuploadで 受け取ります。使用方法により書き換えてください。
  • SKUや価格等は今回使用しなかったため含まれていません。
  • 元となったものでは動作確認をしていますが、編集後動作確認をしていません。
  • 投稿用に編集しているので、不自然な箇所があるかもしれません。

全体

受け取る側

<?php
require_once("./wp-load.php");
require_once('./wp-admin/includes/media.php');
require_once('./wp-admin/includes/file.php');
require_once('./wp-admin/includes/image.php');
mb_internal_encoding("UTF-8");


$title = $_POST["title"];
$explanation = $_POST["Explanation"];
if(title){
$post_id = wp_insert_post( array(
    'post_title' => $title,
    'post_content' => "$explanation",
    'post_status' => 'publish',
    'post_type' => "product",
) );

$total = count($_FILES['upload']['name']);
$mediaarray = array();
for( $i=0 ; $i < $total ; $i++ ) {
    $attachment_id = uploadimg($i,$post_id);
    array_push($mediaarray,$attachment_id);
    }
$revarray = array_reverse($mediaarray);
setimg($post_id,$revarray);

function uploadimg($i,$post_id){
    $tmpFilePath = $_FILES['upload']['tmp_name'][$i];
    if ($tmpFilePath != ""){
    $upload = wp_upload_bits($_FILES["upload"]["name"][$i], null, file_get_contents($_FILES["upload"]["tmp_name"][$i]));
    if (!$upload_file['error']) {
    $filename = $upload['file'];
    chmod($filename, 0777);
    $wp_filetype = wp_check_filetype($filename, null);
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_parent' => $post_id,
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attachment_id = wp_insert_attachment($attachment, $filename, $post_id);
    if (!is_wp_error($attachment_id)) {
        $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename);
        wp_update_attachment_metadata( $attachment_id,  $attachment_data );
        return $attachment_id;
    }
}
}
}

function setimg($post_id, $image_id_array) {
    set_post_thumbnail($post_id, $image_id_array[0]);
    if(sizeof($image_id_array) > 1) { 
        array_shift($image_id_array);
        update_post_meta($post_id, '_product_image_gallery', implode(',',$image_id_array)); 
    }
}
?>

送る側

<form action="[パス]" enctype="multipart/form-data" method="post">
<input type="text" name="title">
<input type="text" name="Explanation">
<input type="file" multiple accept="image/*" name="upload[]">
</form>

解説は後で書きます

0
0
0

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
0
0