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

NO IMAGE

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);