wordpressで投稿ページから文字と画像を別に抽出

wordpress

記事から文字だけを抽出する方法

<?php
//記事データを抽出
$content  = get_the_content();
//記事データからタグデータを除いて抽出
$text     = strip_tags(strip_shortcodes($content));
echo $text;
?>

記事から画像だけを抽出する方法

<?php

global $post;
//グローバル変数から現在の記事IDを取得
$post_id = $post->ID;

//投稿中のすべての添付データの情報をオブジェクト形式(デフォルト)で取得
$attachments = get_children(array('post_parent' => $post_id, 'post_type' => 'attachment'));

// オブジェクトの配列をループ処理
foreach ($attachments as $attachment_id => $attachment) {
	// $attachment_id が個々の画像IDとなる
	echo wp_get_attachment_image($attachment_id, 'medium');
}
?>

wp_get_attachment_imageを使うと、サイズ調整が上手くできない場合は wp_get_attachment_image_url を使いurlだけを取得して、<img>タグを使い自分でサイズ指定をすると上手くいきます。

上記の方法だと、データアップロードの情報が記事に紐づいてそのデータしか取れないことが判明・・・
アップロードデータなら上記の方法で上手くいくのですが、今回は投稿記事に乗っている画像データを抽出したいので下記のコードに修正

<?php
//投稿本文を取得
$content = $post->post_content;

//本文内で使用しているショートコードを除去
$content = strip_shortcodes($content);

//本文内に入っている画像を全て抽出
preg_match_all('/<img(?:.*?)src=[\"\'](.*?)[\"\'](?:.*?)>/e', $content, $all_imgs);

//初期化
$complete_imgs = [];

if ($all_imgs[1]) {
	foreach ($all_imgs[1] as $tmp) {
		$original_img = '';
		$images = [];

		//サムネイル記述を削除して、オリジナルの画像パスに変換
		$original_img = preg_replace("/(.+)(-[0-9]+x[0-9]+)(\.[^.]+$)/", "$1$3", $tmp);

		echo "<div style='width:50%; float:left;'>";
		echo "<img width='95%' src='" . $original_img  . " '>";
		echo "</div>";
	}
}

?>