WordPressで投稿時にスラッグを自動でつける
- 2020.02.20
- Wordpress

WordPressで記事を投稿するときにスラッグを自動でつけたいことがあります。
今回は任意の文字列+post_idが公開時に自動で入力されるコードを書きます。
目次
コード
<?php
add_action('transition_post_status', function($new_status, $old_status, $post){
if ($post->post_type === 'post') { // ここは適用したいpost_typeで分岐
// 最初の公開時のみ適用する。
// 2回目以降は適用しないため、自動で入れたくないものは変更できる。
if($new_status == 'publish' && $old_status != 'publish'){
$newpost = array();
$newpost['post_name'] = 'xxxx-' . $post->ID; // xxxx-の部分は任意の文字列
$newpost['ID'] = $post->ID;
wp_update_post($newpost);
}
}
}, 10, 3);
-
前の記事
WordPressでidから本文を取得する 2020.02.13
-
次の記事
記事がありません