0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WordPressのURL構造からcategoryを消す方法【コピペでOK】

Last updated at Posted at 2020-08-22

はじめに

WordPressのカテゴリー配下のURL構造には、/category/の文字列が必ず含まれてしまいます。

例えば、mobileカテゴリーに所属するiphoneというURLスラッグの記事を投稿した場合は、次のようなURL構造になります。

https://hogehoge.com/category/mobile/iphone/

SEO的には、次のようなURL構造にした方が検索エンジンに階層を伝えやすく、/category/を消したくなる場合があると思います。

https://hogehoge.com/mobile/iphone/

この記事では、WordPressのURL構造に含まれる/category/を消す方法について紹介していきます。

WordPressのURLからcategoryを消す

WordPressのfunction.phpに以下のコードを設置してください。
管理画面から、外観→テーマエディター→テーマファイルで編集できます。

function.php
//URL構造からcategoryを削除
function remcat_function($link) {
return str_replace("/category/", "/", $link);
}
add_filter('user_trailingslashit', 'remcat_function');

function remcat_flush_rules() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_action('init', 'remcat_flush_rules');

function remcat_rewrite($wp_rewrite) {
$new_rules = array('(.+)/page/(.+)/?' => 'index.php?category_name='.$wp_rewrite->preg_index(1).'&paged='.$wp_rewrite->preg_index(2));
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_filter('generate_rewrite_rules', 'remcat_rewrite');

上記のコードは、パーマリンク設定が/%category%/%postname%/でサブカテゴリがある場合は、404になってしまい残念ながら使えません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?