wordpress カスタム投稿 いろいろ

### カスタム投稿タイプの追加

function create_post_type() {
  register_post_type( 'report',
    array(
      'labels' => array(
        'name' => __( 'レポート' ),
        'singular_name' => __( 'レポート' )
      ),
      'public' => true,
      'has_archive' => true,
      'supports' => array('title','editor','custom-fields'),
    )
  );
}
add_action( 'init', 'create_post_type' );

### 月別アーカイブ一覧の表示
Custom Post Type Permalinks をインストール
wp_get_archives() に post_type を追加

#### 参考
https://hirashimatakumi.com/blog/4086.html
WordPressでカスタム投稿の月別アーカイブを作る方法がやっと分かった - わぃおがわ

### カスタム投稿一覧表示

archive-スラッグ.phpの中身

// 取得条件
<?php
	$paged = get_query_var('paged') ? get_query_var('paged') : 1 ; //ページの判定
	$args =	array(
			'posts_per_page'   => 5, //表示件数
			'orderby'          => 'date', //ソートの基準
			'order'            => 'DESC', //DESC降順 ASC昇順
			'post_type'        => 'report',
			'paged'            =>  $paged, //ページネーションに必要
			'orderby'		   => 'date',
	);
?>
// 記事一覧表示
<?php
	$the_query = new WP_Query( $args );
	if ( $the_query->have_posts() ) {
	    while ( $the_query->have_posts() ) {
	        $the_query->the_post();
	        echo '<p>';
		        the_title();
	        echo '</p>';
	        // the_content();
	    }
	    wp_reset_postdata();
	}
?>
// ページャー
<?php
  global $wp_rewrite;
  $paginate_base = get_pagenum_link(1);
  if(strpos($paginate_base, '?') || ! $wp_rewrite->using_permalinks()){
  $paginate_format = '';
  $paginate_base = add_query_arg('paged','%#%');
  }
  else{
  $paginate_format = (substr($paginate_base,-1,1) == '/' ? '' : '/') .
  user_trailingslashit('page/%#%/','paged');;
  $paginate_base .= '%_%';
  }
  echo paginate_links(array(
  'base' => $paginate_base,
  'format' => $paginate_format,
  'total' => $wp_query->max_num_pages,
  'type'  => 'list', //ul liで出力
  'mid_size' => 1, //カレントページの前後
  'end_size' => 0,
  'current' => ($paged ? $paged : 1),
  'prev_text' => '',
  'next_text' => '',
  ));
?>

function.phpの中身

<?php
// 最大取得件数を変更
// archive.phpのほうだけだとページャーが
// 管理画面で設定されたもので計算するためおかしくなる
function change_posts_per_page($query) {
    if ( is_admin() || ! $query->is_main_query() )
        return;
    if ( $query->is_archive('report') ) { //カスタム投稿タイプを指定
        $query->set( 'posts_per_page', '20' ); //表示件数を指定
    }
}
add_action( 'pre_get_posts', 'change_posts_per_page' );
?>

#### 参考
WordPressでコンテンツごとにアーカイブページの表示件数を変更するベストな方法 | それからデザイン スタッフブログ
固定ページにカスタム投稿タイプの一覧ページを作成する|カスタム投稿タイプ
WordPressでカスタム投稿のアーカイブでの表示件数を指定する方法 - ホームページ制作代行 株式会社KOP