2017-05-11 7 views
0

私は特定の投稿の特集画像を設定できるスクリプトを作成しようとしています。何らかの理由でそれが機能していません。誰も私になぜ教えてもらえますか?Wordpress - プログラムによる記事の紹介画像のアップロード

$post_id = ... // We get the ID from the form 

if (isset($_FILES['thumbnail'])) { 
    $uploaded_file = $_FILES['userfile']; 
    $filename  = $uploaded_file['name']; 
    $tmp_file  = $uploaded_file['tmp_name']; 
    $upload_dir = wp_upload_dir(); 
    $end_file  = $upload_dir['path']."/$filename"; 

    move_uploaded_file($tmp_file, $end_file); 

    $wp_filetype = wp_check_filetype($filename, null); 
    $attachment = array(
     'post_mime_type' => $wp_filetype['type'], 
     'post_title'  => sanitize_file_name($filename), 
     'post_content' => '', 
     'post_status' => 'inherit' 
    ); 
    $attach_id = wp_insert_attachment($attachment, $end_file, $post_id); 
    set_post_thumbnail($post_id, $attach_id); 
} 
+0

をあなたが新しい投稿を作成するときに機能を備えた画像セクションを追加するためのUIを使用していない理由は? – Exprator

+0

これを行うには、ネイティブWPバックエンドにアクセスするためのインターフェースを作成する必要があります。もちろん、私はそのようにすることを好むだろう:) –

答えて

0

ファイルをアップロードする正しい名前は何ですか?あなたはIfステートメントとちょうど次の行に異なるのparamの名前を使用している

if (isset($_FILES['thumbnail'])) { 
    $uploaded_file = $_FILES['userfile']; 

だから必ずそれが正しいのparamからファイル情報を引っ張っsを作ります。 また、次のコードのために誤ったファイルのパスを渡している。

$wp_filetype = wp_check_filetype($filename, null); 

それは代わりに$filenameで、$end_fileでなければなりません。

だから、正しいコードは次のようになります。

$post_id = ... // We get the ID from the form 

if (isset($_FILES['thumbnail'])) { 
    $uploaded_file = $_FILES['userfile']; 
    $filename  = $uploaded_file['name']; 
    $tmp_file  = $uploaded_file['tmp_name']; 
    $upload_dir = wp_upload_dir(); 
    $end_file  = $upload_dir['path']."/$filename"; 

    move_uploaded_file($tmp_file, $end_file); 

    $wp_filetype = wp_check_filetype($end_file, null); 
    $attachment = array(
     'guid'   => $wp_upload_dir['url'] . '/' . basename($end_file), 
     'post_mime_type' => $wp_filetype['type'], 
     'post_title'  => sanitize_file_name($filename), 
     'post_content' => '', 
     'post_status' => 'inherit' 
    ); 
    $attach_id = wp_insert_attachment($attachment, $end_file, $post_id); 

    // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. 
    require_once(ABSPATH . 'wp-admin/includes/image.php'); 

    // Generate the metadata for the attachment, and update the database record. 
    $attach_data = wp_generate_attachment_metadata($attach_id, $end_file); 
    wp_update_attachment_metadata($attach_id, $attach_data); 

    set_post_thumbnail($post_id, $attach_id); 
} 
+0

それは問題だった...私はファイルを識別するために間違った文字列を使用していた...申し訳ありません。それはかなりばかげたバグです... 8-( –

+0

@EnriqueMorenoTentは全く心配ありません。バグはちょうどバグです、誰もバグを作るので、全く心配はありません:-) – Codemole

+0

ありがとうございます。時間を節約しました;) –

関連する問題