問題描述

我正在經營一個物業網點,許多物業都在公寓樓內出售。

因為這樣的內容,編輯者做的是建立一個包含所有細節的 post /property,然後使用一個重複的 post plugin 來建立其他的。

每次他們複製一個帖子/財產,他們更改標題以反映屬性編號,也許更改幾個後設資料 E.G 價格。

他們忘記做的是擦掉 s lug 聲,並從標題中產生一個新的。這是從第一個屬性輸入的一個例子:

merle-court-plot-50-182-carlton-vale-nw6-5hh

但是當他們複製的 s s 變成:

merle-court-plot-50-182-carlton-vale-nw6-5hh-2
merle-court-plot-50-182-carlton-vale-nw6-5hh-2-2
merle-court-plot-50-182-carlton-vale-nw6-5hh-2-2-2
merle-court-plot-50-182-carlton-vale-nw6-5hh-2-2-2-2
etc

但是當他們改變標題時,lug 子會更好:

merle-court-plot-51-182-carlton-vale-nw6-5hh
merle-court-plot-52-182-carlton-vale-nw6-5hh
merle-court-plot-53-182-carlton-vale-nw6-5hh
merle-court-plot-54-182-carlton-vale-nw6-5hh
etc

所以我的問題:

How do I force the slug to be re-generated on post save, after they have updated the property title?

這個 CPT 的插頭應該始終是自動生成的,從不需要手動設定它。

最佳解決方案

最簡單的解決方法可能是:

function myplugin_update_slug( $data, $postarr ) {
    if ( ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
        $data['post_name'] = sanitize_title( $data['post_title'] );
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'myplugin_update_slug', 99, 2 );

次佳解決方案

另外,從 sanitize_title_with_dashes()透過 wp_unique_post_slug()執行 slug 以確保它是唯一的。如果需要,它將自動附加’-2’,’-3’ 等。

第三種解決方案

而不是替換空格,您應該使用功能 sanitize_title()的構建,這將為您處理更換。

喜歡這個:

sanitize_title( $post_title, $post->ID );

此外,您應該使用獨特的 s 。。您可以使用 wp_unique_post_slug()功能獲得

所以把它放在一起,解決方案可能是:

function myplugin_update_slug( $data, $postarr ) {
    if ( ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
        $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'] ), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent'] );
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'myplugin_update_slug', 99, 2 );

第四種方案

我已經預訂了一段時間的東西是以下 (尚未測試的),

Source LINK

//add our action
add_action( 'save_post', 'my_save_post', 11, 2 );

function my_save_post($post_id, $post){

   //if it is just a revision don't worry about it
   if (wp_is_post_revision($post_id))
      return false;

   //if the post is an auto-draft we don't want to do anything either
   if($post->post_status != 'auto-draft' ){

       // unhook this function so it doesn't loop infinitely
       remove_action('save_post', 'my_save_post' );

      //this is where it happens -- update the post and change the post_name/slug to the post_title
      wp_update_post(array('ID' => $post_id, 'post_name' => str_replace(' ', '-', $_POST['post_title'])));

      //re-hook this function
      add_action('save_post', 'my_save_post' );
   }
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。