Created
March 15, 2020 10:00
-
-
Save kaoru-fukusato/af7c62295c889fe926028e4e996f13f5 to your computer and use it in GitHub Desktop.
記事ランダムをショートコードとして使う場合
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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