WordPressランダムに1件記事を表示させるショートコード ( カスタム投稿、任意の件数に対応 )

広告WordPress・PHP を学べる本

Amazonのアソシエイトとして、WordPress functions.phpは適格販売により収入を得ています。

概要説明

ランダムに記事を表示させたい場合に使用すると便利なショートコード。通常の記事、カスタム投稿、表示件数など調整が可能。

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]'); ?>
<?php echo do_shortcode('[post_rand post_type=news posts_per_page=2]'); ?>

関連機能

  1. 指定期間内に公開した記事タイトルに一括で新着表示をつける

  2. WordPress の外部リンクに nofollow・別タブ・アイコンをまとめて付ける:プラグイン External Links と、プラグインなしのコード

  3. WordPress ウィジェットでショートコードを使えるようにする

サイドバー

よく使うカスタマイズ

最近の記事

Profile

PAGE TOP