# wp:特定のカスタム投稿タイプのパーマリンクを変更する ###### tags: `WordPress` ## やりたいこと https://my-site.com/archives/person/kyary/ の `archives/` を消したい。 ※ パーマリンクに`数字ベース` 、`/%postname%/` を使っている場合、必ずURLに`archives/` が入ってしまう ## URLの自作は、かなり大変 前提として、functions.phpで自作で`rewrite`ルールを設定するのは、かなり大変。 やるならfunctions.phpで`add_rewrite_rule`を追加していく。 参考:ASOBI / fuctions.php ```php= function custom_rewrite_rule() { add_rewrite_rule('^schedule/monthly/?$','index.php?post_type=schedule&schedule_mode=monthly','top'); add_rewrite_rule('^schedule/monthly/([0-9]{4})/([0-9]{2})/?$','index.php?post_type=schedule&schedule_y=$matches[1]&schedule_m=$matches[2]&schedule_mode=monthly','top'); add_rewrite_rule('^schedule/weekly/?$','index.php?post_type=schedule&schedule_mode=weekly','top'); add_rewrite_rule('^schedule/weekly/([0-9]{4})/([0-9]{2})/([0-9]{2})/?$','index.php?post_type=schedule&schedule_y=$matches[1]&schedule_m=$matches[2]&schedule_d=$matches[3]&schedule_mode=weekly','top'); add_rewrite_rule('^schedule/daily/?$','index.php?post_type=schedule&schedule_mode=daily','top'); add_rewrite_rule('^schedule/daily/([0-9]{4})/([0-9]{2})/([0-9]{2})/?$','index.php?post_type=schedule&schedule_y=$matches[1]&schedule_m=$matches[2]&schedule_d=$matches[3]&schedule_mode=daily','top'); add_rewrite_rule('^talent/artist/?$','index.php?taxonomy=talent_cat&term=artist','top'); add_rewrite_rule('^talent/creator/?$','index.php?taxonomy=talent_cat&term=creator','top'); add_rewrite_rule('^talent/model/?$','index.php?taxonomy=talent_cat&term=model','top'); add_rewrite_rule('^talent/actor/?$','index.php?taxonomy=talent_cat&term=actor','top'); } add_action('init', 'custom_rewrite_rule', 10, 0); ``` - 正規表現の知識が必要 - DB自体を書き換えることになるので、サーバー側のキャッシュが残ったり、何かとトラブル多め ## 今回の実装方法 カスタム投稿タイプのパーマリンクを設定するプラグイン「Custom Post Type Permalinks」を使う。 #### 1. プラグインをいれる #### 2. functions.php内のカスタム投稿タイプの設定で、`'rewrite' => array( 'with_front' => false )`にする。 ```php= register_post_type( 'person', array( 'label' => 'パーソン', 'public' => true, 'has_archive' => true, 'menu_position' => 5, 'supports' => array('title','editor','author'), 'rewrite' => array( 'with_front' => false ), ) ); ``` ↑この設定が有るか無いかによって、設定できるパーマリンクが変わる。 例えば、この設定が無い場合、 ``` https://my-site.com/archives/person/kyary/ ``` となるのが、この設定を入れる事によって、 ``` https://my-site.com/person/kyary/ ``` というようにできる。 #### 3. パーマリンクの設定 ![](https://i.imgur.com/GXszaBD.png) ### 参考 http://morilog.com/wordpress/post_type/custom_post_type_permalinks_plugin/