WordPress 埋め込みブロックのスタイル変更

functions.php を編集する前に

functions.phpは、WordPressの動作に関わる重要なファイルです。記述を間違えると、Webサイトが表示されなくなったり、管理画面にログインできなくなったりする場合があります。

編集する前に、必ず現在のfunctions.phpの内容をバックアップしておきましょう。
また、コードを追加する際は、既存のコードを誤って削除したり変更したりしないよう注意してください。
コードを追加した後にエラーが発生した場合は、追加したコードを確認し、元の状態に戻してください。

functions.phpの編集は、内容を確認したうえで慎重に行ってください。

functions.php

下記コードの追加で

  • カードサイズ 幅いっぱい
  • 画像 120pxの正方形
  • 抜粋 最大3行
  • 抜粋文字数 150文字

となります。

/* WordPress埋め込みカードを調整 */
function custom_wordpress_embed_style() {
	wp_add_inline_style(
		'wp-embed-template',
		'
		/* カードを幅いっぱいにする */
		.wp-embed {
			width: 100% !important;
			max-width: none !important;
			box-sizing: border-box;
		}

		/* 画像を120pxの正方形にする */
		.wp-embed-featured-image {
			width: 120px !important;
			height: 120px !important;
			overflow: hidden;
		}

		.wp-embed-featured-image img {
			width: 100% !important;
			height: 100% !important;
			object-fit: cover !important;
		}

		/* 抜粋を最大3行にする */
		.wp-embed-excerpt {
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 3;
			overflow: hidden;
		}
		'
	);
}
add_action( 'embed_head', 'custom_wordpress_embed_style' );


/* 埋め込みiframeを幅いっぱいにする */
function custom_wordpress_embed_iframe() {
	?>
	<style>
		.wp-embedded-content {
			width: 100% !important;
			max-width: 100% !important;
		}
	</style>
	<?php
}
add_action( 'wp_head', 'custom_wordpress_embed_iframe' );


/* 埋め込み画像を正方形として扱う */
function custom_embed_thumbnail_shape() {
	return 'square';
}
add_filter( 'embed_thumbnail_image_shape', 'custom_embed_thumbnail_shape' );


/* 埋め込みカードの抜粋を長くする */
function custom_embed_excerpt_more_length( $length ) {
	if ( is_embed() ) {
		return 150;
	}
	return $length;
}
add_filter( 'excerpt_length', 'custom_embed_excerpt_more_length' );