Learning site for website creation

030:スラッグ名が日本語の時に自動で「投稿タイプ-投稿id」へ変更

公開日:2020年11月08日

スラッグ名が日本語の時に自動的に「投稿タイプ-投稿id」へ変更します。半角英数でスラッグを設定した場合は適用されません。

functions.php

/*********************************
  スラッグ名が日本語だったら自動的に「投稿タイプ-id」へ変更
 **********************************/
function auto_post_slug($slug, $post_ID, $post_status, $post_type)
{
  if (preg_match('/(%[0-9a-f]{2})+/', $slug)) {
    $slug = utf8_uri_encode($post_type) . '-' . $post_ID;
  }
  return $slug;
}
add_filter('wp_unique_post_slug', 'auto_post_slug', 10, 4);