ランダム記事リストをサイドバーに表示する方法

今回は、ランダムで記事リストを表示するサイドバーウィジェットを作る方法を解説します。
投稿ページのサイドバーに置くことで、訪問者に毎回違う記事をアピールできます。

実装のポイント

  • WordPress の WP_Widget を拡張してカスタムウィジェットを作成
  • orderby => 'rand' でランダム表示
  • ウィジェットのタイトルや表示件数を設定可能

functions.php にコードを追加


// ランダム関連記事ウィジェット(アイキャッチ付き・回り込み)
class Random_Related_Posts_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'random_related_posts', // ウィジェットID
            'ランダム関連記事',     // ウィジェット名
            array('description' => 'サイドバーにアイキャッチ付きのランダム関連記事を表示')
        );
    }

    // ウィジェット表示
    public function widget($args, $instance) {
        echo $args['before_widget'];

        $title = !empty($instance['title']) ? $instance['title'] : '関連記事';
        echo $args['before_title'] . esc_html($title) . $args['after_title'];

        $num_posts = !empty($instance['num_posts']) ? absint($instance['num_posts']) : 5;

        $related = new WP_Query(array(
            'posts_per_page' => $num_posts,
            'post__not_in'   => array(get_the_ID()),
            'orderby'        => 'rand',
            'category__in'   => wp_get_post_categories(get_the_ID())
        ));

        if ($related->have_posts()) {
            echo '<ul class="sidebar-related-posts">';
            while ($related->have_posts()) {  
                $related->the_post();
                echo '<li class="sidebar-related-item">';
                echo '<a href="' . get_permalink() . '">';
                if (has_post_thumbnail()) {
                    echo get_the_post_thumbnail(get_the_ID(), 'thumbnail');
                }
                echo '<span class="sidebar-related-title">' . get_the_title() . '</span>';
                echo '</a></li>';
            }
            echo '</ul>';
        }

        wp_reset_postdata();
        echo $args['after_widget'];
    }

    // ウィジェット設定フォーム
    public function form($instance) {
        $title = isset($instance['title']) ? $instance['title'] : '関連記事';
        $num_posts = isset($instance['num_posts']) ? $instance['num_posts'] : 5;
        ?>
        <p>
            <label>タイトル:</label>
            <input class="widefat" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" />
        </p>
        <p>
            <label>表示件数:</label>
            <input class="tiny-text" name="<?php echo $this->get_field_name('num_posts'); ?>" type="number" step="1" min="1" value="<?php echo esc_attr($num_posts); ?>" size="3" />
        </p>
        <?php
    }

    // 更新処理
    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['num_posts'] = absint($new_instance['num_posts']);
        return $instance;
    }
}

// ウィジェット登録
function register_random_related_posts_widget() {
    register_widget('Random_Related_Posts_Widget');
}
add_action('widgets_init', 'register_random_related_posts_widget');

汎用CSS


/* サイドバー関連記事(アイキャッチ付き・回り込み) */
.sidebar-related-posts {
    list-style: none;
    padding-left: 0;
    margin: 0 0 0 -20px; /* サイドバーの余白に合わせて調整 */
}

.sidebar-related-item {
    margin-bottom: 10px;
    overflow: hidden; /* floatを使った回り込みを確実に */
}

.sidebar-related-item img {
    float: left;         /* 左に回り込み */
    width: 60px;         /* サムネイルサイズ */
    height: 60px;
    object-fit: cover;
    margin-right: 8px;   /* 画像とタイトルの間隔 */
    border-radius: 4px;  /* 角丸 */
}

.sidebar-related-item .sidebar-related-title {
    display: block;
    font-size: 14px;
    line-height: 1.2;
    color: #0073aa;
}

.sidebar-related-item a:hover .sidebar-related-title {
    text-decoration: underline;
}
    

設置方法

  1. 上記の PHP コードを子テーマの functions.php に追加
  2. WordPress 管理画面 → 外観 → ウィジェット → サイドバーに「ランダム関連記事」を追加
  3. タイトルと表示

    (例)
    ウィジェット
    (例)
    ランダム表示