概要説明
ランダムに記事を表示させたい場合に使用すると便利なショートコード。通常の記事、カスタム投稿、表示件数など調整が可能。
パラメーターを指定することでカスタム投稿、任意の件数をランダムに取得可能
functions.php
/*----------------------------------------------------
投稿をランダムに1件取得
----------------------------------------------------*/
if ( ! function_exists( 'get_the_post_rand' ) ) {
function get_the_post_rand( $atts ) {
$atts = shortcode_atts( array(
'post_type' => 'post',
'posts_per_page' => 1, // 取得件数
'not_in' => '',
), $atts );
$args = array(
'post_type' => sanitize_key( $atts['post_type'] ),
'posts_per_page' => absint( $atts['posts_per_page'] ),
'orderby' => 'rand', // ランダム指定
'post__not_in' => array_filter( array_map( 'absint', explode( ',', $atts['not_in'] ) ) ), // 自記事を除外したりする場合に使用
);
$the_query = new WP_Query( $args );
$html = '';
if ( $the_query->have_posts() ) {
$html .= '<div>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$html .= '<article><div><h3><a href="' . esc_url( get_permalink() ) . '" title="' . esc_attr( get_the_title() ) . '">' . esc_html( get_the_title() ) . '</a></h3></div></article>';
}
$html .= '</div>';
}
wp_reset_postdata();
// ショートコードは echo ではなく return で返す
return $html;
}
add_shortcode( 'post_rand', 'get_the_post_rand' );
}
以前のコードは echo で出していたため、ショートコードを置いた場所ではなく本文の先頭に出ていました。また、関数があるかの確かめが別の関数名(add_category_color_field)になっていました。文字を組み立てて return で返し、URL とタイトルをエスケープする形に直しました(2026/10/18・作業環境で、置いた場所に 2 件出ることを確かめています)。
ショートコードの実行方法 投稿をランダムに1件
<?php echo do_shortcode('[post_rand]'); ?>
カスタム投稿を2件ランダムに取得
<?php echo do_shortcode('[post_rand post_type=news posts_per_page=2]'); ?>


