
初心者なりに調べて次のコードまで考えてみたのですが、どうしてもできません。どうぞお手柔らかにお願い致します。
「wp_insert_post_data」を使い、記事の公開前にスラッグを書き換えようと考えています。
しかし次のコードをfunctions.phpに記入しましたが、スラッグはタイトルと同じになってしまいます。
ランダムの生成箇所は問題なさそうで、2つあるifに原因があるように思うのすけれど、どのようにして書けばよろしいでしょうか?
どなたかお優しい方がいらっしゃいましたら教えて下さい。
PHP
1function my_post( $data , $postarr ) { 2 // newsの場合 3 if ( $data['post_type'] == 'news' ){ 4 // ランダム生成 5 $str = array_merge(range('a', 'z'), range('0', '9'), range('A', 'Z"')); 6 $r_str = null; 7 for ($i = 0; $i < 8; $i++) { 8 $r_str .= $str[rand(0, count($str))]; 9 } 10 // 初めて作るnewsの場合にスラッグをランダムにする 11 if ( empty( $postarr ) ){ 12 $data['post_status'] = 'publish'; 13 $data['post_title'] = ''; 14 $data['post_name'] = $r_str; 15 } 16 } 17 return $data; 18} 19add_action( 'wp_insert_post_data', 'my_post', 99, 2 ); 20
上のコードは以下のページを参考にして自分なりに考えたものでして、丸投げではございません。ご理解頂ければ幸いでございます。
https://teratail.com/questions/106842
https://rfs.jp/sb/wordpress/wp-lab/wp_insert_post_data.html
https://worklog.be/archives/2108
上のコードに沿って教えてくださる回答者さんがいらっしゃいましたら宜しくお願い致します。



回答2件
あなたの回答
tips
プレビュー