ランダム記事リストを固定ページにショートコードで表示する方法
ランダム記事リストショートコード(件数・列数・抜粋・画像サイズ変更可能)
// ランダム記事ショートコード
function random_posts_shortcode($atts) {
$atts = shortcode_atts(array(
'count' => 4, // 表示件数
'cols' => 2, // 列数
'excerpt_words' => 20, // 抜粋文字数
'image_size' => 'thumbnail' // アイキャッチ画像サイズ
), $atts, 'random_posts');
$args = array(
'posts_per_page' => intval($atts['count']),
'orderby' => 'rand',
'post_status' => 'publish'
);
$query = new WP_Query($args);
if (!$query->have_posts()) return '<p>記事はありません。</p>';
$output = '<div class="random-posts" style="display:grid; grid-template-columns: repeat(' . intval($atts['cols']) . ', 1fr); gap:1em;">';
while($query->have_posts()) {
$query->the_post();
$thumb = has_post_thumbnail() ? get_the_post_thumbnail(get_the_ID(), $atts['image_size']) : '';
$excerpt = wp_trim_words(get_the_excerpt(), intval($atts['excerpt_words']), '...');
$output .= '<div class="random-post-item">';
$output .= $thumb;
$output .= '<div class="post-title"><a href="' . get_permalink() . '">' . get_the_title() . '</a></div>';
$output .= '<div class="post-excerpt">' . $excerpt . '</div>';
$output .= '<a href="' . get_permalink() . '" class="read-more-button" style="display:inline-block; margin-top:5px; padding:5px 10px; background:#1a73e8; color:#fff; text-decoration:none; border-radius:4px;">続きを読む</a>';
$output .= '</div>';
}
$output .= '</div>';
wp_reset_postdata();
return $output;
}
add_shortcode('random_posts', 'random_posts_shortcode');
補足:
表示件数や列数はショートコードの属性で変更可能です。
例: [random_posts count="6" cols="3"]
表示件数や列数はショートコードの属性で変更可能です。
例: [random_posts count="6" cols="3"]
汎用CSS(必要に応じてテーマに合わせ調整)
/*ランダム記事リストを固定ページにショートコードで表示*/
.random-posts {
list-style: none;
margin: 0;
padding: 0;
}
.random-post-item {
border: 1px solid #ddd;
padding: 10px;
display: flex;
flex-direction: column;
align-items: flex-start;
}
.random-post-item img {
width: 100%;
height: auto;
object-fit: cover;
margin-bottom: 10px;
}
.random-post-item .post-title {
font-weight: bold;
margin-bottom: 5px;
}
.random-post-item .post-excerpt {
font-size: 0.9em;
color: #555;
}
/* スマホ用に1列にする */
@media screen and (max-width: 768px) {
.random-posts {
grid-template-columns: 1fr !important;
}
}
補足:
アイキャッチ画像の幅を 100% にしています。つまり、親コンテナ(グリッドのカラム幅)に合わせて自動的に伸縮する設定です。
アイキャッチ画像の幅を 100% にしています。つまり、親コンテナ(グリッドのカラム幅)に合わせて自動的に伸縮する設定です。
使い方例
- 件数6、列3、抜粋60文字、アイキャッチサイズ「medium」:
[random_posts count="6" cols="3" excerpt_words="50" image_size="medium"]
(例)Lightning
- 件数4、列2、抜粋50文字、アイキャッチサイズ「large」:
[random_posts count="4" cols="2" excerpt_words="60" image_size="large"]
(例)Lightning
代用プラグイン
もしPHPを編集できない場合は、ランダム記事表示用のプラグイン(例: WP Random Post Widget)を使うことで同様の機能を実装可能です。
ランダム記事表示ではなく、新着順表示用のプラグイン(例:Content Views)も同じような機能を実装可能です。
まとめ
このショートコードを使うと、ホームページや固定ページでランダム記事を自由に列数・件数を指定して表示できます。
アイキャッチ、タイトル、抜粋、そして「続きを読む」ボタンもセットで表示されます。