ショートコード
[linkcard "https://yahoo.co.jp/"]
上記のショートコードで指定のURLのOGP情報を取得してページ上に表示するサンプルコードです。
functions.php
まずfunctions.php内に下記コードを追加します。
/* ショートコード(リンクカード) */
function get_ogp($atts){
$html = file_get_contents($atts[0]);
$match = preg_match_all( '#<meta property=["\']og:([^"\']+)["\'] content=["\']([^"\']+)["\'].*?>#', $html, $result );
if($match > 0){
$count = count($result[1]);
for( $i = 0; $i < $count; $i++ ) {
$opg[$result[1][$i]] = $result[2][$i];
}
}
$title = $opg['title'];
$url = $opg['url'];
$site_name = $opg['site_name'];
$image = $opg['image'];
if(empty($image)){ $image = "https://"; }
$description = $opg['description'];
$str = "";
if(!empty($title)):
$str .= "<div class=\"linkcard\">";
$str .= "<div class=\"linkcard-img\">";
$str .= "<img src=\"" . $image . "\" width=\"100%\" height=\"\" alt=\"" . $title . "\" />";
$str .= "</div>";
$str .= "<div class=\"linkcard-info\">";
$str .= "<p class=\"linkcard-url\">" . $url . "</p>";
$str .= "<p class=\"linkcard-title\">" . $title . "</p>";
$str .= "</div>";
$str .= "<a href=\"" . $url . "\" class=\"linkcard-anchor\">続きを読む</a>";
$str .= "</div>";
endif;
return $str;
}
add_shortcode('linkcard','get_ogp');
/* ボタン追加 */
add_action('admin_print_footer_scripts', function () {
if (wp_script_is('quicktags')){
echo <<<EOF
<script type="text/javascript">
QTags.addButton('link-button', 'リンクカード', '[linkcard "', '"]', '', '', 1);
</script>
EOF;
}
},100);
リンクカードを表示するショートコード部と、テキストエディタ上でショートコードを組み込むボタンのふたつについて記述をしています。
リンクカード部のHTML構造
出力されるHTML構造は下記のようになりますので、こちらをCSSでデザインしてゆけばOKです。
<div class="linkcard">
<div class="linkcard-img">
<img src="画像URL" width="100%" height="" alt="タイトル" />
</div>
<div class="linkcard-info">
<p class="linkcard-url">https://yahoo.co.jp</p>
<p class="linkcard-title">タイトル</p>
</div>
<a href="" class="linkcard-anchor">続きを読む</a>
</div>
HTML構造を変更したい場合は、ショートコード部の出力コードを変更することで対応できます。