Skip to content

Instantly share code, notes, and snippets.

@ics-ikeda
Last active June 8, 2018 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ics-ikeda/24c22a876226545bf9b92fbf6cc1486e to your computer and use it in GitHub Desktop.
Save ics-ikeda/24c22a876226545bf9b92fbf6cc1486e to your computer and use it in GitHub Desktop.
WordPressでimgタグの代わりにamp-imgタグを使う方法
/**
* コンテンツのHTML文字列からimg要素をamp-img要素に変換します。
* 動作には「phpQuery-onefile.php」が必要です。
* ダウンロードして参照できるようにしておいてください。
*
* @param string
* @return string
*/
function convertImgToAmpImg($the_content)
{
// PHPのパスを解決(相対パスだとライブラリを読み込めないため)
require_once(dirname(__FILE__) . "/libs/phpQuery-onefile.php");
// 仮想DOMを構築(phpQueryで走査するため)
$html = <<<HTML
<html>
<body>{$the_content}</body>
</html>
HTML;
// DOMを構築
$dom = phpQuery::newDocument($html);
// img要素を探し出して、繰り返す
foreach ($dom->find("img") as $img) {
// 参照を取る
$pqImg = pq($img);
// 属性値をコピーする
$obj["src"] = $pqImg->attr("src");
$obj["width"] = $pqImg->attr("width");
$obj["height"] = $pqImg->attr("height");
$obj["srcset"] = $pqImg->attr("srcset");
$obj["alt"] = $pqImg->attr("alt");
// sizes属性は表示崩れの可能性があるのでコピーしない
// src 属性がなければ変換しない
if (empty($obj["src"])) {
continue;
}
// width と height がなければ強制的に 16:9 を代入する
if (empty($obj["width"]) || empty($obj["height"])){
$obj["width"] = 960;
$obj["height"] = 540;
}
// 属性をコピーする
$attrStr = [];
foreach ($obj as $key => $value) {
if (!empty($value)) {
$attrStr[] = "$key=\"$value\"";
}
}
// layout属性を追加する
$attrStr[] = 'layout="responsive"';
// img要素をamp-img要素に置き換える
// コピーした属性値をくっつける
$pqImg->replaceWith("<amp-img " . join(" ", $attrStr) . " />");
}
// contentの内容を返す
return $dom->find("body")->html();
}
<section itemprop="articleBody" role="main">
<?php
// img タグを amp-img に置換する
add_filter('the_content', 'convertImgToAmpImg', 9999);
// 記事コンテンツを出力する
the_content();
?>
</section>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment