プラグイン無しでリンクカードを作る方法:WordPress

WordPressでプラグイン無しでブログカードを作る方法をメモ。
プラグインを使用する場合Pz-LinkCardが有名かと思いますが、
サイトが重くなったりでプラグインを使いたくない場合には今回ご紹介する方法をおすすめします。
方法は簡単で下記のコードをコピペで使用できます。
functions.phpへ追加
まず、下記のコードをfunctions.phpに追加します。
// 抜粋文を取得
function ltl_get_the_excerpt($post_id){
global $post;
$post_bu = $post;
$post = get_post($post_id);
setup_postdata($post_id);
$output = get_the_excerpt();
$post = $post_bu;
return $output;
}
//ブログカード用ショートコード
function clink_scode($atts) {
extract(shortcode_atts(array(
'url'=>"",
'title'=>"",
'excerpt'=>""
),$atts));
$id = url_to_postid($url);//URLから投稿IDを取得
$no_image = 'noimageに指定したい画像パス';//アイキャッチ画像がない場合の画像を指定
//タイトルを取得
if(empty($title)){
$title = esc_html(get_the_title($id));
}
//抜粋文を取得
if(empty($excerpt)){
$excerpt = esc_html(ltl_get_the_excerpt($id));
}
//アイキャッチ画像を取得
if(has_post_thumbnail($id)) {
$img = wp_get_attachment_image_src(get_post_thumbnail_id($id),'medium');
$img_tag = "<img src='" . $img[0] . "' alt='{$title}'/>";
}else{
$img_tag ='<img src="'.$no_image.'" alt="" width="'.$img_width.'" height="'.$img_height.'" />';
}
$clink .='
<div class="linkcard">
<a href="'. $url .'">
<div class="thumb">'. $img_tag .'</div>
<div class="txt">
<div class="ctitle">'. $title .' </div>
<div class="cexcerpt">'. $excerpt .'</div>
</div>
</a>
</div>';
return $clink;
}
add_shortcode("clink", "clink_scode");
ショートコードの出力
あとは表示したい箇所に
[clink url=”ここにURL” title=”独自で設定したいタイトルがある場合は記述” excerpt=”ここに独自の抜粋文”]
で完成です。
titleやexcerptは自動取得で問題ない場合は必要ありませんので
[clink url=”ここにURL”]
で大丈夫です。
↓出力サンプル例
WordPressのおすすめ参考書
bookfan 1号店 楽天市場店
¥3,300 (2026/01/20 15:42時点 | 楽天市場調べ)

