[WordPress]記事内で他の記事を紹介するショートコードを作成する方法

こんばんは、webエンジニアのゾノ( @ozonosho )です。
さて、今日のブログではWordPressの記事内で他の記事を紹介するショートコードを作成する方法を紹介したいと思います。
具体的には、このサイトでも度々使用している下記の記事紹介欄を利用できるようになります。
他の記事を紹介する際にアイキャッチや本文が含まれることで興味を持たれやすくなるのでぜひお試しください。
それでは早速、実装方法を見ていきましょう。
WordPressの記事内で他の記事を紹介するショートコードを作成する方法
実装は簡単で、functions.phpに下記のコードを追加してください。
function insertPost($atts) {
extract(shortcode_atts(array(
'id' => "",
), $atts));
$html = '';
if($id) {
$post = get_post($id);
if($post) {
$html .= '<div class="insert-post">';
$html .= '<a target="_blank" href="' . get_post_permalink($post->ID) . '">';
$html .= '<div class="img">';
$html .= get_the_post_thumbnail($post->ID, 'thumbnail');
$html .= '</div>';
$html .= '<div class="text">';
$html .= '<p class="title">' . $post->post_title . '</p>';
$html .= '<p class="content">' . mb_substr($post->post_content, 0, 表示したい文字数) . '...</p>';
$html .= '<span class="go">→この記事を読む</span>';
$html .= '</div>';
$html .= '</a>';
$html .= '</div>';
}
}
return $html;
}
add_shortcode('insert', 'insertPost');
あとは記事の本文内で[insert id=記事ID]と書くだけで指定したIDの記事紹介欄を表示できます。
ちなみにこの記事のIDは3077なので[insert id=3077]と書くと、下記のように表示されます。
デザインはCSSで調整しているので、ご自身の好みに合わせて設定してください。
参考までに当サイトで使用しているCSSを公開します。
.insert-post {
border: solid 1px #ccc;
margin-bottom: 10px;
background-color: #fff;
}
.insert-post a {
padding: 10px;
display: block;
overflow: hidden;
position: relative;
}
.insert-post .img {
width: 180px;
float: left;
margin-right: 15px;
}
.insert-post .img img {
width: 180px;
height: 120px;
object-fit: cover;
}
.insert-post .text {
padding-left: 195px;
}
.insert-post .text p {
line-height: 1.55;
}
.insert-post .text .title {
color: #000;
font-weight: bold;
margin-top: 2px;
margin-bottom: 10px;
}
.insert-post .text .content {
color: #555;
font-size: 13px;
margin-bottom: 0;
}
.insert-post .text .go {
position: absolute;
bottom: 6px;
right: 5px;
line-height: 1;
display: inline-block;
font-size: 13px;
font-weight: bold;
}
.insert-post a:hover {
text-decoration: none;
background-color: #eee;
}
.insert-post a:hover .text .go {
text-decoration: underline;
}
これで、記事紹介欄の作成は完了です!
他の記事を紹介する際にアイキャッチや本文が含まれることで興味を持たれやすくなるので、ぜひお試しください。
おわりに
以上、今回の記事ではWordPressの記事内で他の記事を紹介するショートコードを作成する方法を紹介させていただきました。
当サイトではWordPressのカスタマイズ依頼を請け負っています。実現したい機能・要望がある方はぜひ下記ページよりご相談ください。











