Created
March 16, 2020 04:01
-
-
Save kaoru-fukusato/b1b8cc573af6b4c9c3b97ce1026995c9 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 カテゴリID 個数] | |
このように記載すると指定カテゴリIDの記事を指定個数分、リンク付きで、アイキャッチ画像とタイトルを表示します。 | |
※カテゴリID=0を指定するとすべての投稿を対象とします。 | |
プラグイン実装(ソースをほぼ加工なしで表示しています) | |
・class指定やCSS定義などは省略しています。 | |
ショートコード実装 | |
/////////////////// | |
function shortcode_random_posts( $param ) { | |
return random_posts($param[0] , $param[1]); //0:カテゴリーID(0はカテゴリ指定なし) 1:表示記事数 | |
} | |
add_shortcode('random_posts','shortcode_random_posts'); | |
///////////////////////////// | |
本体部分 | |
<?php | |
function random_posts( $category_id , $show_posts) { | |
if ( $show_posts <= 0 ) { $show_posts = 1; } //0以下はありえないのでとりあえず1にする | |
if ( $category_id == 0 ) { //カテゴリ無関係にランダム表示 | |
$args = array( | |
'posts_per_page' => $show_posts , | |
'orderby' => 'rand', | |
'post_type' => 'post', | |
'post_status' => 'publish' | |
); | |
} else { //カテゴリ指定してランダム表示 | |
$args = array( | |
'posts_per_page' => $show_posts , | |
'category' => $category_id , | |
'orderby' => 'rand', | |
'post_type' => 'post', | |
'post_status' => 'publish' | |
); | |
} | |
ob_start(); // バッファリング開始 | |
$posts_array = get_posts( $args ); | |
?> | |
<ul class=""> | |
<?php | |
foreach ( $posts_array as $post ) { | |
$post_id = $post->ID; | |
$post_title = get_the_title( $post_id ); | |
$post_link = get_permalink( $post_id ); | |
?> | |
<li> | |
<a href="<?php echo $post_link;?>"> | |
<?php | |
if (get_the_post_thumbnail( $post_id, 'thumbnail' )) { | |
echo get_the_post_thumbnail( $post_id, 'thumbnail' ); | |
} else { | |
echo '<img src="アイキャッチがない時に代わりに表示する画像のURL" class="">'; | |
} | |
?> | |
</a> | |
<a href="<?php echo $post_link;?>"><?php echo $post_title; ?></a> | |
</li> | |
<?php | |
} | |
wp_reset_postdata(); | |
?> | |
</ul> | |
<?php | |
$return_strings = ob_get_contents(); // バッファリング取得 | |
ob_end_clean(); // バッファリング終了 | |
return $return_strings; | |
} | |
/////////////////////////////// | |
本ページ下記の表示の元となったショートコード | |
[random_posts 0 5] ※全記事からランダムに5記事 | |
[random_posts 7370 5] ※ID=7370カテゴリ(diaryカテゴリ)からランダムに5記事 | |
[random_posts 7517 5] ※ID=7517カテゴリ(worksカテゴリ)からランダムに5記事 | |
実行結果(ランダムに表示されるので読み込むごとに表示される投稿が変わります) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment