Skip to content

Instantly share code, notes, and snippets.

@kaoru-fukusato
Created March 15, 2020 10:00
Show Gist options
  • Save kaoru-fukusato/af7c62295c889fe926028e4e996f13f5 to your computer and use it in GitHub Desktop.
Save kaoru-fukusato/af7c62295c889fe926028e4e996f13f5 to your computer and use it in GitHub Desktop.
記事ランダムをショートコードとして使う場合
[random_posts limit=5]
<?php
function random_posts($attrs = array()){
ob_start();
$limit = !empty($attrs['limit']) ? $attrs['limit'] : 0;
?>
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'rand', // 記事のランダム表示設定
'posts_per_page' => $limit,
);
$posts_query = new WP_Query( $args );
if ($posts_query->have_posts()) :
while ($posts_query->have_posts()) : $posts_query->the_post(); ?>
/* 繰り返し表示させる部分 */
<div class="post-item">
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<?php echo get_the_excerpt(); ?>
</div>
<?php endwhile;
endif; ?>
<?php
return ob_get_clean();
}
add_shortcode('random_posts','random_posts');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment