問題描述
我正在用他的 WordPress 網站幫助我的父親。它擁有超過 1700 個職位,擁有 TITLES IN UPPERCASE 。
我們想將這些更改為資料庫中的”Title Case”(可能使用 this PHP script) 。
WordPress「到標題案例」plug-in 在模板級更改大小寫 – 我們想在資料庫級別更改它。
將指令碼應用於 WordPress 資料庫中的所有標題是什麼?我可以從頭開始編寫一些程式碼,但我猜測現有的程式碼/方法可以在所有標題中應用一個函式/方法。
最佳解決方案
更新帖子
$all_posts = get_posts(
'posts_per_page' => -1,
'post_type' => 'post'
);
foreach ( $all_posts as $single ) {
wp_update_post( array(
'ID' => $single->ID,
'post_title' => to_title_case( $single->post_title ) // see function below
));
}
將字串轉換為”Title Case”
而且,與 WP 無關,為了完整起見:
function to_title_case( $string ) {
/* Words that should be entirely lower-case */
$articles_conjunctions_prepositions = array(
'a','an','the',
'and','but','or','nor',
'if','then','else','when',
'at','by','from','for','in',
'off','on','out','over','to','into','with'
);
/* Words that should be entirely upper-case (need to be lower-case in this list!) */
$acronyms_and_such = array(
'asap', 'unhcr', 'wpse', 'wtf'
);
/* split title string into array of words */
$words = explode( ' ', mb_strtolower( $string ) );
/* iterate over words */
foreach ( $words as $position => $word ) {
/* re-capitalize acronyms */
if( in_array( $word, $acronyms_and_such ) ) {
$words[$position] = mb_strtoupper( $word );
/* capitalize first letter of all other words, if... */
} elseif (
/* ...first word of the title string... */
0 === $position ||
/* ...or not in above lower-case list*/
! in_array( $word, $articles_conjunctions_prepositions )
) {
$words[$position] = ucwords( $word );
}
}
/* re-combine word array */
$string = implode( ' ', $words );
/* return title string in title case */
return $string;
}
顯然,這兩個單詞列表可以擴充套件 – lower-case 列表尤其是更多介詞,這些列表在當前站點上經常使用的首字母縮略詞。
無論如何,WP-specific 部分只是上層程式碼塊。
次佳解決方案
您可以在檢視帖子時更改帖子標題:
add_action( 'the_post', 'wpse_94856_title_update' );
function wpse_94856_title_update( $post )
{
if ( empty ( $post->post_title ) )
return;
$new_title = mb_convert_case( $post->post_title, MB_CASE_TITLE, "UTF-8" );
if ( $post->post_title === $new_title )
return;
wp_update_post(
array (
'ID' => $post->ID,
'post_title' => $new_title
)
);
// $post is passed by reference, so we update this property in real time
$post->post_title = $new_title;
}
這只是一個基於 this answer 的想法。沒有測試。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。