カスタム投稿を設定し、パーマリンクを書き換え可能にする

2019.9.27

カスタム投稿はプラグインに頼らず自作でも充分可能です。以下のようなコードをfunctions.phpに書き加えることで、カスタム投稿「店舗情報」を作り、パーマリンクも英数字ベースで書き換えできるようにします。

register_post_type(
  'purchase',
  array(
    'label' => '店舗情報',
    'public' => true,
    'menu_position' => 5,
    'hierarchical' => true,
    'has_archive' => true,
    'supports' => array(
                    'title',
                    'editor',
                    'thumbnail',
                    'revisions',
                    'excerpt',
                    'page-attributes',
                    'custom-fields',
                    )
  )
);
register_taxonomy_for_object_type('category', 'purchase');
register_taxonomy_for_object_type('post_tag', 'purchase');
}
add_action('init', 'add_custom_post');

add_filter( 'rewrite_rules_array', 'my_rewrite_rules_array' );
function my_rewrite_rules_array( $rules ) {
  $new_rules = array(
    'archives/news/([0-9]+)/?$' => 'index.php?post_type=news&p=$matches[1]',
  );

  return $new_rules + $rules;
}

固定ページ同様にカテゴリーやタグを共用できる仕様とする場合は上記コードのみでOKです。