クラシックエディター(TinyMCE)では画像を「右寄せ」や「左寄せ」にするとfloatが適用されるが、このfloatの解除方法がない。テキストエディタでタグ打ちができればclear: bothを挿入して解除できるが知識が必要。
ビジュアルエディタしか使えない場合、バック部ラウンドで処理する必要がある。
そこで、alignleftやalignrightが付与されたfloat画像をdivタグでラップしてクラスを付ける処理をする。
functions.php(クラスは、class=”imgWrapp”)
※デフォルトの投稿タイプ「post」にだけ適用する
正規表現ベースの軽量版
function wrap_aligned_images_lightweight($content) {
if (!is_singular('post')) {
return $content;
}
// <p>タグ内に複数のimgタグがあり、すべてがalignクラス付きならラップ
$pattern = '/<p>\s*((?:<img[^>]+class="[^"]*\balign(?:left|right|center)\b[^"]*"[^>]*>\s*){1,})<\/p>/i';
$replacement = '<div class="imgWrapp">$1</div>';
return preg_replace($pattern, $replacement, $content);
}
add_filter('the_content', 'wrap_aligned_images_lightweight');
DOM 操作版(全ての要素をチェックするため処理不可が少しだけ増える 通常の投稿なら問題ないレベル)
function wrap_aligned_images_preserve_position($content) {
if (!is_singular('post')) {
return $content;
}
libxml_use_internal_errors(true);
$html = '<?xml encoding="UTF-8"><body>' . $content . '</body>';
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$bodyList = $dom->getElementsByTagName('body');
if ($bodyList->length === 0) return $content;
$body = $bodyList->item(0);
$newBody = $dom->createDocumentFragment();
foreach ($body->childNodes as $node) {
if ($node->nodeType === XML_ELEMENT_NODE && $node->tagName === 'p') {
$imgNodes = [];
foreach ($node->childNodes as $child) {
if ($child->nodeType === XML_ELEMENT_NODE && $child->tagName === 'img') {
$class = $child->getAttribute('class');
if (preg_match('/align(left|right|center)/', $class)) {
$imgNodes[] = $child;
}
}
}
if (count($imgNodes) > 0 && count($node->childNodes) === count($imgNodes)) {
$wrapper = $dom->createElement('div');
$wrapper->setAttribute('class', 'imgWrapp');
foreach ($imgNodes as $img) {
$wrapper->appendChild($img->cloneNode(true));
}
$newBody->appendChild($wrapper);
} else {
$newBody->appendChild($node->cloneNode(true));
}
} else {
$newBody->appendChild($node->cloneNode(true));
}
}
$body->nodeValue = '';
$body->appendChild($newBody);
$new_content = '';
foreach ($body->childNodes as $child) {
$new_content .= $dom->saveHTML($child);
}
return $new_content;
}
add_filter('the_content', 'wrap_aligned_images_preserve_position');
cssでimgWrappにflexboxを適用する
画像は最大横幅270pxを設定してwidth:100%でレスポンシブにも対応させる
/* 回り込み画像の処理ここから */
#main #singlePosts .imgWrapp {
display: flex;
gap: 10px;
width: 100%;
}
#main #singlePosts img.alignleft,
#main #singlePosts img.alignright,
#main #singlePosts img.aligncenter {
max-width: 270px;
width: 100%;
margin: 0;
float: none;
}
/* 回り込み画像の処理ここまで */