特定のカスタムフィールドのある投稿を指定した件数ランダムに表示する
以下のスニペットは、カスタムフィールド「photo」を持つ、投稿10件を表示する。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php $i = 0; /* 表示件数の指定*/ $max = 10; /* カスタムフィールドの名称*/ $custom_field_name = 'photo'; $args = array('meta_key' => $custom_field_name //カスタムフィールドの名称 , 'post_type' => 'post' //投稿を , 'post_status' => 'public' //公開しているものから , 'orderby' => 'rand' //ランダムに , 'nopaging' => true //ページングをしないで、 , 'post__not_in' => get_option( 'sticky_posts' ) //stickyは、除外して //抽出してね ); query_posts($args); if( have_posts() ){ while(have_posts()){ the_post(); the_title('<p>','</p>'); $i++; /* 必要な件数確保したら、ループを抜ける*/ if( $i > $max ){ break; } } } /* 足りない時のダミー*/ if( $i < $max ){ for ( $i; $i < $max; $i++ ){ echo '<p>none</p>'; } } wp_reset_query(); ?> |