【WordPress】ワードプレスにプラグインなしでブログカードを貼る方法

今回はプラグインなしでブログカードを貼る方法の紹介です。

いつものように、これから紹介するコードを丸っとコピペするだけ
下記のようなブログカードを記事に入れることが出来ます。
DEMO

functions.phpに追記する

下記のコードを丸っとfunctions.phpにコピペします。

// 記事IDを指定して抜粋文を取得
function ltl_get_the_excerpt($post_id){
global $post;
$post_bu = $post;
$post = get_post($post_id);
setup_postdata($post_id);
$output = get_post_meta($post_id,'_yoast_wpseo_metadesc',true);//YoastSEOから
$post = $post_bu;
return $output;
}

//ショートコード
function nlink_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.'" />';
}

$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

下記をコピペすると、ページの最初にあるDEMOと同じデザインになります。

.blog-card div {
margin: 0!important
}
.blog-card {
background: #fff;
border: 1px solid #eee;
word-wrap: break-word;
max-width: 100%;
-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:hover {
cursor: pointer;
background: #f8f8f8
}
.blog-card a {
text-decoration: none;
}
.blog-card-thumbnail {
width: 35%;
display: table-cell;
vertical-align: middle;
padding: 10px 0 10px 10px;
}
.blog-card-thumbnail img {
padding: 0;
border: solid 1px #eee
}
.blog-card-content {
display: table-cell;
padding: 20px
}
.blog-card-title {
font-size: 108%;
margin: 5px 10px 25px 0px;
font-weight: bold;
padding-bottom: 10px
}
.blog-card-excerpt {
color: #4c4c4c;
margin: 0 10px 5px 0;
overflow: hidden;
text-overflow: ellipsis;
}
.blog-card .clear {
clear: both;
}
.single iframe {
margin: 0 auto;
width: 560px;
height: 315px
}

@media screen and (max-width: 500px) {
.blog-card:before {
font-size: .56em
}
.blog-card-title {
font-size: .70em
}
.blog-card-excerpt {
font-size: .60em
}
.single iframe {
width: 100%!important;
height: 200px
}
}

説明文が長いとスマホ版で少し縦長になってしまうので、
.blog-card-excerptを非表示にしてしまってもいいかもしれません。

使い方

使い方は下記のショートコードを入れるだけです。

[nlink url="記事のURL"]

説明文を変更したい場合は下記を追加します。
excerpt="説明文"

[nlink url="記事のURL" excerpt="説明文"]

Thanks : https://macoblog.com/wp-blogcard-notplugin/

メリットとデメリット

ブログカードは見た目が良く、目立ち安い反面、

画像によっては広告と間違われてしまうので注意しましょう。