ホームページ制作覚書

WordPress

「先頭に固定表示」を指定した記事→その記事を除いてループ表示【WordPress】

  1. 表示させたい記事の合計件数を指定
  2. 先頭固定した記事を表示
  3. 先頭固定した記事数を表示させたい記事の合計件数から差し引き→通常のループへ
  4. 通常ループから先頭固定した記事を省き、残りの数の記事を表示
<?php 
$list_cnt = 6; //表示させたい記事の合計件数
$sticky = get_option('sticky_posts'); //先頭固定の記事
if ( !empty($sticky) ) $list_cnt -= count($sticky); //先頭固定の記事がある場合は、その件数を「$list_cnt」の値から引く
if ( count($sticky) > 0 ):
    $the_query = new WP_Query(array(
        'post_type'=> 'post' , 
        'cat'=> 4,
        'post__in' => $sticky,
    ));?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <dl>
            <dt><?php the_title(); ?><span><?php echo get_the_date(); ?></span></dt>
            <dd><?php the_content(); ?></dd>
        </dl>
    <?php endwhile; ?>
<?php endif; ?>
<?php if ( $list_cnt > 0 ): //先頭固定以外の記事の表示
    $the_query = new WP_Query(array(
        'post__not_in' => get_option( 'sticky_posts' ), 
        'post_type'=> 'post' , 
        'cat'=> 4,
        'posts_per_page' => $list_cnt,
        'ignore_sticky_posts' => 1,
    ));?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <dl>
            <dt><?php the_title(); ?><span><?php echo get_the_date(); ?></span></dt>
            <dd><?php the_content(); ?></dd>
        </dl>
    <?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>

TAG : 

CATEGORY : 

Arrival