Learning site for website creation

24:共通処理を関数化:サブループ

公開日:2018年11月05日 更新日:2018年11月13日

複数テンプレートで使用する処理は関数化して「functions.php」に定義しておくことで修正対応しやすくなります。

サブループ表示関数定義

functions.php

サブループコードをカスタマイズして関数化

// サブループ
function getSubloop($search, $title) {
  $the_query = new WP_Query($search);
  $code = '';
  if($the_query->have_posts()) {
    $code .= '<div class="sub-loop">'.PHP_EOL;
    $code .= '<div class="inner">'.PHP_EOL;
    $code .= '<h1>'.$title.'</h1>'.PHP_EOL;
    while($the_query->have_posts()) {
      $the_query->the_post();
      $code .= '<a class="post-link" href="'.get_the_permalink().'">'.PHP_EOL;
      $code .= '<h2 class="title">'.get_the_title().'</h2>'.PHP_EOL;
      $code .= '</a>'.PHP_EOL;
    }
    $code .= '</div><!-- /.inner -->'.PHP_EOL;
    $code .= '</div><!-- /.sub-loop -->'.PHP_EOL;
  }
  wp_reset_postdata();
  return $code;
}

定義した関数を利用

front-page.php

ハイライト部分書き換え

<?php get_header(); ?>

  <div class="content">
    <div class="main">

<?php /***** サブループ条件 *****/ ?>
<?php // 先頭固定表示 ?>
<?php
$sticky = get_option( 'sticky_posts' );
$args = array(
    'post_type' => 'post',
    'posts_per_page' => 3,
    'post__in' => $sticky,
    'orderby' => 'id',
    'order' => 'DESC'
);
echo getSubloop($args, '先頭固定表示');
?>
<?php /***** サブループ終了 *****/ ?>


<?php /***** サブループ条件 *****/ ?>
<?php // その他記事 ?>
<?php
$args = array(
  'post_type' => 'post',
  'posts_per_page' => 5,
  'category_name' => '未分類',
  'ignore_sticky_posts' => 1,
  'orderby' => 'id',
  'order' => 'DESC'
);
echo getSubloop($args, 'その他最新記事');
?>
<?php /***** サブループ終了 *****/ ?>


      <div class="main-loop">
        <div class="inner">
<?php /***** メインループ開始 *****/ ?>
<?php if (have_posts()) :?>
<?php while (have_posts()) : the_post(); ?>
<?php $id = get_the_ID(); ?>
<?php // リンク ?>
<a class="post-link <?php echo 'post-id'.$id; ?>" href="<?php the_permalink(); ?>">

<?php // アイキャッチ画像 ?>
  <div class="thumbnail">
<?php echo getThumbnail(); ?>
  </div>

<?php // タイトル ?>
  <h2 class="title"><?php the_title(); ?></h2>

<?php // カテゴリ文字列 ?>
<?php echo getCatList(); ?>

<?php // タグ文字列 ?>
<?php echo getTagList(); ?>

<?php // 抜粋文 ?>
  <div class="excerpt"><?php the_excerpt(); ?></div>

<?php // 公開日時 ?>
  <div class="release-date">公開日時:<?php the_time('Y年m月d日'); ?></div>

<?php // 最終更新日時 ?>
  <div class="modified-date">最終更新日時:<?php the_modified_date('Y年m月d日'); ?></div>
</a>

<?php endwhile; ?>
<?php else: ?>
<div class="no-post">
  <div class="inner">
    <p>記事が存在しません</p>
  </div><!-- /.inner -->
</div><!-- /.no-post -->
<?php endif; ?>
<?php /***** メインループ終了 *****/ ?>

<?php // ページネーション ?>
<?php if (pagination()) : ?>
    <div class="pagination"><?php echo pagination(); ?></div>
<?php endif; ?>

        </div><!-- /.inner -->
      </div><!-- /.main-loop -->
    </div><!-- /.main -->
    <?php get_sidebar(); ?>
  </div><!-- /.content -->


<?php
get_footer();

このページで出てくる関数

オリジナル関数

getSubloop()

 

欠席者対応:wireframe08

同じタグのコンテンツ