[WordPress]OGP画像をパターンによって出し分け
突発的に必要になったため、備忘録としてメモ。
「OGP画像はすでにあるけれど、これ以降の投稿は任意の画像をOGPに設定したいな!(テヘッ)」
・・・みたいな時に役立つかと思います。
functions.php
function delete_domain_from_url( $url ) { if ( preg_match( '/^http(s)?:\/\/[^\/\s]+(.*)$/', $url, $match ) ) { $url = $match[2]; } return $url; }
header.php
<?php if ( is_single()) : ?> <?php $customfield = get_post_meta($post->ID, 'CF_NAME', true); ?> <?php if( empty($customfield) ): ?> <meta property="og:image"content="<?phpechohome_url() .delete_domain_from_url(wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' )[0]); ?>"> <meta name="twitter:image"content="<?phpechohome_url() .delete_domain_from_url(wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' )[0]); ?>"> <?php else: ?> <meta property="og:image"content="<?php $fileid = get_post_meta($post->ID, CF_NAME, false); $file = wp_get_attachment_image_src($fileid[0], 'full'); echo$file[0]; ?>"/> <meta name="twitter:image"content="<?php $fileid = get_post_meta($post->ID, CF_NAME, false); $file = wp_get_attachment_image_src($fileid[0], 'full'); echo$file[0]; ?>"> <?php endif; ?> <?php else : ?> <!-- DEFAULT OGP --> <meta property="og:image"content="<?phpechohome_url() ?>/img/ogp.png"> <meta name="twitter:image"content="<?phpechohome_url() ?>/img/ogp.png"> <?php endif; ?>
参考: