記事を投稿した時に、新規でプログラムから記事を投稿するプログラムを作成しました。
プログラムは、正常に動作しているのですが、更新した時に、更新したページで、「�PNG IHDR��<q� IDATx���w�]Օ���'�X�rR�*+�2 !�$r29��6�m������x�o>�^w��
w�� ���& 」という文字化けが大量に出現し、ページの下部に更新したページが表示されている状態です。
メディアライブラリに画像を追加するプログラムを追加してからその状態が起きました。
メディアライブラリには、「001.png」が正常に入っていました。
メディアライブラリPHPから投稿する方法の参考サイト:https://www.imamura.biz/blog/16736
文字化けを解消する方法がわかる方いましたら教えてください。
function get_article_created_time() { remove_action('save_post', 'get_article_created_time'); //無限loop解除用 if (empty($_POST['publish'])) { } else { if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { // 自動保存時 return $post_id; // 何もしない } elseif (!empty($_POST)) { global $post; $get_title = $post->post_title; //記事タイトル取得 $get_content = $post->post_content; //記事本文取得 $get_tag = get_the_tags(); $get_tag_id = array(); foreach ($get_tag as $tag) { $get_tag_id[] = $tag->name; } $get_tag_ids = implode(',', $get_tag_id); $my_post = array( 'post_type' => 'post', //投稿タイプ 'post_title' => $get_name, //記事タイトル 'post_status' => 'publish', //投稿ステータス 'post_content' => $get_content, //記事本文 'post_category' => array($get_category_id), //記事カテゴリー 'tags_input' => array($get_tag_ids), /タグ 'post_name' => 'd-' . $get_name//スラッグ ); $post_id = wp_insert_post($my_post); // $filename はアップロード用ディレクトリにあるファイルのパス。 $filename = 'http://localhost/test/wp-content/uploads/001.png'; $wp_filetype = wp_check_filetype(basename($filename), null); //ファイル名の拡張子、mime形式を配列で取得 $wp_upload_dir = wp_upload_dir(); //ファイルのアップロード先ディレクトリを取得 // この添付ファイルを紐付ける親投稿の ID。 $parent_post_id = $post->ID; $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . basename($filename), 'post_mime_type' => $wp_filetype['type'], //mime形式を指定「image/png」「image/jpeg」など 'post_title' => 'd-'.preg_replace('/.[^.]+$/', '', basename($filename)), //ファイル名を指定 'post_content' => '', //空の文字列を指定 'post_status' => 'publish' //投稿ステータスを指定 ); $attach_id = wp_insert_attachment($attachment, $filename, $parent_post_id); require_once( ABSPATH . 'wp-admin/includes/image.php' ); //「wp_generate_attachment_metadata()」を使う場合には、このファイルを事前に読み込んでおくこと $attach_data = wp_generate_attachment_metadata($attach_id, $filename); //組み合わせて使う wp_update_attachment_metadata($attach_id, $attach_data); //組み合わせて使う } } } add_action('save_post', 'get_article_created_time');
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。