警告
ブログカードでWarningが出てたので修正
OpenGraphを使ったブログカードを使っていましたが、昨日画面にwarningが出ていることに気づきました。どうも、ogpを取得できていません。ローカルでは取得できているので、エックサーバーだとダメなのかもと、色々修正を試みましたが、うまくいかないのです。どうやったらogpを取得できるのか、サーバーにphpファイルをあげて試してみると、file_get_contentsだと取れるみたい。加えて、faviconも取得したかったのですが、どうにもうまくいかない。AIに相談しつつ試行錯誤するとduckduckgoだと取れるよというのでやってみると、本当に取れました。以下、書いてもらったコードです。
function show_Linkcard($atts) {
extract(shortcode_atts(array('url'=>"", 'title'=>"", 'excerpt'=>""), $atts));
if (empty($url)) return '';
$Link_title = $title;
$Link_description = $excerpt;
$Link_site_name = '';
$options = array(
'http' => array(
'method' => 'GET',
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\r\n",
'timeout' => 10
),
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
)
);
$context = stream_context_create($options);
$html = @file_get_contents($url, false, $context);
if ($html !== false) {
$encoding = mb_detect_encoding($html, 'UTF-8, SJIS, EUC-JP, JIS, ASCII', true);
if ($encoding && $encoding !== 'UTF-8') {
$html = mb_convert_encoding($html, 'UTF-8', $encoding);
}
if (preg_match('/<meta[^>]*property=["\']og:site_name["\'][^>]*content=["\']([^"\']+)["\']/i', $html, $matches)) {
$Link_site_name = $matches[1];
}
if (empty($Link_title)) {
if (preg_match('/<meta[^>]*property=["\']og:title["\'][^>]*content=["\']([^"\']+)["\']/i', $html, $matches)) {
$Link_title = $matches[1];
} elseif (preg_match('/<title>([^<]+)<\/title>/i', $html, $matches)) {
$Link_title = trim($matches[1]);
}
}
if (empty($Link_description)) {
if (preg_match('/<meta[^>]*property=["\']og:description["\'][^>]*content=["\']([^"\']+)["\']/i', $html, $matches)) {
$Link_description = wp_trim_words($matches[1], 60, '…');
} elseif (preg_match('/<meta[^>]*name=["\']description["\'][^>]*content=["\']([^"\']+)["\']/i', $html, $matches)) {
$Link_description = wp_trim_words($matches[1], 60, '…');
}
}
}
if (empty($Link_title)) {
$Link_title = $url;
}
$favicon = '';
$host = parse_url($url, PHP_URL_HOST);
if (!empty($host)) {
$searchFavcon = 'https://icons.duckduckgo.com/ip3/' . $host . '.ico';
$favicon = '<img class="favicon" src="' . esc_url($searchFavcon) . '" width="16" height="16" data-no-lazy="1" alt="">';
}
$sc_Linkcard = '';
$sc_Linkcard .= '<a href="' . esc_url($url) . '" target="_blank" class="blogcard-anchor">';
$sc_Linkcard .= '<div class="blogcard opacityTargets">';
$sc_Linkcard .= '<div class="blogcard_content">';
$sc_Linkcard .= '<div class="blogcard_title">' . esc_html($Link_title) . '</div>';
$sc_Linkcard .= '<div class="blogcard_excerpt">' . esc_html($Link_description) . '</div>';
$sc_Linkcard .= '<div class="blogcard_link">' . $favicon . ' ' . esc_html($Link_site_name) . '</div>';
$sc_Linkcard .= '</div>';
$sc_Linkcard .= '</div>';
$sc_Linkcard .= '</a>';
return $sc_Linkcard;
}
add_shortcode("sc_Linkcard", "show_Linkcard");コメント
選曲
The Moldau