プラグインなしでWordPressにブログカードを設置する方法
今回は表題通り。プラグインをつかわずに、WordPressにブログカードを設定する方法を紹介します。
WordPressで記事を書いていると、他の日に書いた記事等を参照してもらいたいことがあります。そんなときに役立つのがブログカード。はてなブログでお馴染みのアレです。内部リンクをただのテキストリンクからブログカードに置き換えることで、ユーザーの目にも留まりやすく、サイトの離脱率も下がると言われています。
WordPressにはブログカードを作るプラグインもありますが、自作も出来ます。あまりプラグインを入れたくない、という方はぜひ。
プラグインをつかわずにブログカードを実装するための下準備
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 nlink_scode($atts) {
extract(shortcode_atts(array(
'url'=>"",
'title'=>"",
'excerpt'=>""
),$atts));
$id = url_to_postid($url);
$img_width ="120";
$img_height = "120";
$no_image = 'アイキャッチ画像がない場合の画像をパス指定';
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),array($img_width,$img_height));
$img_tag = "<img src='" . $img[0] . "' alt='{$title}' width=" . $img[1] . " height=" . $img[2] . " />";
}else{
$img_tag ='<img src="'.$no_image.'" alt="" width="'.$img_width.'" height="'.$img_height.'" />';
}
$nlink .='
<div class="blog-card">
<a href="'. $url .'">
<div class="blog-card-thumbnail">'. $img_tag .'</div>
<div class="blog-card-content">
<div class="blog-card-title">'. $title .' </div>
<div class="blog-card-excerpt">'. $excerpt .'</div>
</div>
<div class="clear"></div>
</a>
</div>';
return $nlink;
}
add_shortcode("nlink", "nlink_scode");
CSS
CSSには下記を記述。
.blog-card {
background: #f5f6f7;
border:1px solid #ddd;
word-wrap:break-word;
max-width:100%;
margin: 30px;
transition: all 0.4s;
}
.blog-card:hover {
background: #eee;
}
.blog-card a {
text-decoration: none;
}
.blog-card-title {
color: #337ab7;
display: block;
}
.blog-card-thumbnail {
float:left;
padding:10px;
}
.blog-card-thumbnail img {
display: block;
padding: 0;
-webkit-transition: 0.3s ease-in-out;
-moz-transition: 0.3s ease-in-out;
-o-transition: 0.3s ease-in-out;
transition: 0.3s ease-in-out;
}
.blog-card-content {
line-height:120%;
}
.blog-card-title {
padding:10px 10px 10px 0;
font-size:100%;
font-weight: bold;
line-height: 1.5em;
color: #333;
}
.blog-card-excerpt {
color:#333;
margin:0 10px 10px;
line-height: 1.5em;
font-size: 14px;
height: 80px;
overflow: hidden;
}
.blog-card .clear {
clear: both;
}
このブログカードの使い方
ブログカードを表示するにはショートコードを使います。ショートコードは下記です。
[nlink url="ここに記事リンク"]
これを記事内のブログカードを表示させたい箇所に記述し、リンク先記事のURLを書きます。このブログでもこちらの方法でブログカードを実装しています。