プラグインなしで、ワードプレス投稿記事をランダムに表示するときの方法。
タイトルのみ、タイトルと抜粋、タイトルとサムネイルバージョンのコピペ用ソース。
‘numberposts’の部分で表示する記事数を設定。今回は3件ずつの例。
テンプレートの表示したい部分に記述
<div> <h3>ランダムに記事を表示</h3> <ul> <?php $args = array( 'numberposts' => 3, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1); $rand_posts = get_posts( $args ); foreach( $rand_posts as $post ) : ?> <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> </ul> </div>
HTML出力例
<div> <h3>ランダムに記事を表示</h3> <ul> <li><a href="ri-mode.com/memo" title="記事のタイトル1">記事のタイトル1</a></li> <li><a href="ri-mode.com/memo" title="記事のタイトル2">記事のタイトル2</a></li> <li><a href="ri-mode.com/memo" title="記事のタイトル3">記事のタイトル3</a></li> </ul> </div>
テンプレートの表示したい部分に記述
<div> <h3>ランダムに記事を表示</h3> <ul> <?php $args = array( 'numberposts' => 3, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1); $rand_posts = get_posts( $args ); foreach( $rand_posts as $post ) : ?> <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><p><?php the_excerpt(); ?></p></li> <?php endforeach; ?> </ul> </div>
HTML出力例
<div> <h3>ランダムに記事を表示</h3> <ul> <li><a href="ri-mode.com/memo" title="記事のタイトル1">記事のタイトル1</a><p>記事のタイトル1の抜粋</p></li> <li><a href="ri-mode.com/memo" title="記事のタイトル2">記事のタイトル2</a><p>記事のタイトル2の抜粋</p></li> <li><a href="ri-mode.com/memo" title="記事のタイトル3">記事のタイトル3</a><p>記事のタイトル3の抜粋</p></li> </ul> </div>
テンプレートの表示したい部分に記述
<div> <h3>ランダムに記事を表示</h3> <ul> <?php $args = array( 'numberposts' => 3, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1); $rand_posts = get_posts( $args ); foreach( $rand_posts as $post ) : ?> <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> <p> <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"> <?php if ( has_post_thumbnail() ): ?> <?php echo get_the_post_thumbnail(); ?> <?php else: ?> <img src="<?php echo get_template_directory_uri(); ?>/images/no_image.png" alt="NO IMAGE" title="NO IMAGE" /> <?php endif; ?> </a> </p></li> <?php endforeach; ?> </ul> </div>
HTML出力例
<div> <h3>ランダムに記事を表示</h3> <ul> <li><a href="ri-mode.com/memo" title="記事のタイトル1">記事のタイトル1</a> <p><a href="ri-mode.com/memo" title="記事のタイトル1"><img src="ri-mode.com/memo/tumbnail1.jpg"></a></p> </li> <li><a href="ri-mode.com/memo" title="記事のタイトル2">記事のタイトル2</a> <p><a href="ri-mode.com/memo" title="記事のタイトル2"><img src="ri-mode.com/memo/tumbnail2.jpg"></a></p> </li> <li><a href="ri-mode.com/memo" title="記事のタイトル3">記事のタイトル3</a> <p><a href="ri-mode.com/memo" title="記事のタイトル3"><img src="ri-mode.com/memo/tumbnail3.jpg"></a></p> </li> </ul> </div>
参考サイト
How to Display Random Posts in WordPress without a Plugin