メニュー

東京・小金井市のWEB制作会社の豆知識

MEMORANDUM

WordPress(ワードプレス)のショートコードを使ってブログカードを実装する

ワードプレスで記事を投稿する際に、まとめ記事や拡張記事などで過去記事を引用したい場合もあります。
既存の埋め込み機能を使う方法もありますが、思い通りの内容を表示したい場合は、再利用可能な「ブログカード」を用意するのが便利なので実装方法をメモ。

functions.php

function func_blogcard($atts) {
	
	$atts = shortcode_atts(array(
		'url' => '',
	), $atts, 'blogcard');
	
	$url = $atts['url'];
	$post_id = url_to_postid($url); //URLから投稿IDを取得
	
	//タイトルを取得
	$title = esc_html(get_the_title($post_id));
	//抜粋文を取得
	if(has_excerpt($post_id)) {
		$excerpt = get_the_excerpt($post_id);
	}else{
		$excerpt = get_bloginfo('description');
	}
	$excerpt = esc_html($excerpt);

	//アイキャッチ画像を取得
	if(has_post_thumbnail($post_id)){
		$img = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'full');
		$img_tag = '<img src="'.$img[0].'" alt="{$title}">';
	}else{
		$img_tag = '<img src="○○.jpg">'; //アイキャッチ画像がない場合の画像
	}

	// ブログカードの内容
	$blogcardlink = '<div class="blogcard">
		<a href="'.$url.'">
		<figure class="blogcard__thumbnail">'.$img_tag.'</figure>
		<dl class="blogcard__inner">
		<dt class="blogcard__title">'.$title.'</dt>
		<dd class="blogcard__excerpt">'.$excerpt.'</dd>
		</dl>
		</a>
		</div>';

	return $blogcardlink;
}

add_shortcode('blogcard', 'func_blogcard');

CSS

.blogcard a {
	display: flex;
	align-items: center;
	padding: 1rem;
	border: #ddd solid 1px;
}
.blogcard__thumbnail {
	width: 33%;
	margin: 0;
}
.blogcard__thumbnail img {
	width: 100%;
	height: auto;
	margin: 0;
}
.blogcard__inner {
	width: calc(67% - 1rem);
	margin: 0 0 0 auto;
}
.blogcard__title {
	margin: 0 0 0.5rem;
	font-weight: bold;
}
.blogcard__excerpt {
	display: -webkit-box;
	-webkit-line-clamp: 3;
	-webkit-box-orient: vertical;
	overflow: hidden;
	font-size: 0.8rem;
}

使用時はショートコードブロックに下記を記載

[blogcard url=https://○○]
RANKING

人気記事

同一カテゴリーの記事