概要説明
ランダムに記事を表示させたい場合に使用すると便利なショートコード。通常の記事、カスタム投稿、表示件数など調整が可能。
パラメーターを指定することでカスタム投稿、任意の件数をランダムに取得可能
functions.php
/*----------------------------------------------------
投稿をランダムに1件取得
----------------------------------------------------*/
if ( !function_exists( 'add_category_color_field' ) ){
function get_the_post_rand( $atts ){
extract( shortcode_atts( array(
'post_type' => 'post',
'posts_per_page' => 1, //取得件数
'not_in' => '',
), $atts) );
$args = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'orderby' => 'rand', // ランダム指定
'post__not_in' => array($not_in), // 自記事を除外したりする場合に使用
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
echo '<div>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<article>';
echo ' <div>';
echo ' <h3><a href="'.get_the_permalink().'" title="'.get_the_title().'">'.get_the_title().'</a></h3>';
echo ' </div>';
echo '</article>';
}
echo '</div>';
}
wp_reset_postdata();
}
add_shortcode('post_rand', 'get_the_post_rand');
}
ショートコードの実行方法 投稿をランダムに1件
<?php echo do_shortcode('[post_rand]'); ?>
カスタム投稿を2件ランダムに取得
<?php echo do_shortcode('[post_rand post_type=news posts_per_page=2]'); ?>



