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をデフォルトで連番化

Last updated at Posted at 2020-12-08

ワードプレスのテーマtwentytwentyを基盤に、新規投稿を作成した際に記事のURLの末尾をデフォルトで連番にする実装を行ったので、備忘録的にこの記事を残す。

環境情報

PHP:version 7.3.12
WordPress:version 5.5.3
WPテーマ:twentytwenty

作業

投稿ページや固定ページのパーマリンクは、デフォルトだとタイトルに入力した文字がそのまま入力されます。
URLに日本語が含まれるとエンコードされてごちゃごちゃしてしまいます。
記事のパーマリンクをデフォルトで連番にしてすっきりさせましょう。

まずは、パーマリンク設定で「カスタム構造」を選択してください。記入欄は %postname% のままで大丈夫です。
次に、functions.php に、下記コードを任意の場所に追記します。

functions.php
// スラッグ名が日本語だったら自動的にnum+id付与へ変更(スラッグを設定した場合は適用しない)
function auto_post_slug( $slug, $post_ID, $post_status ) {
    if ( preg_match( '/(%[0-9a-f]{2})+/', $slug ) ) {
        $slug = 'num-' . $post_ID;
    }
    return $slug;
}
add_filter( 'wp_unique_post_slug', 'auto_post_slug', 10, 4  );

新規投稿をしようとするとパーマリンクにnum-1と表示されているのがわかります。
※日本語云々関係無しに一律で連番にする場合、中の if 文を取り除けば実装できます。

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?