問題描述
在我的主題中,我想定義一系列定製的帖子類型和自定義分類,每個都有自己的定製 s 子; 我的主題的基礎語言是英語,所以 s s 將是英文
例如在定義自定義帖子類型”product” args 時:
'rewrite' => array( 'slug' => 'product' ),
有沒有辦法通過 po /mo 文件翻譯”slug”?我可以把它當作:
'rewrite' => array( 'slug' => __('product', 'mytextdomain') )
還是不行?現在的本地化 s 子的做法是什麼?
最佳解決方案
我不會試圖本地化你的 s 子。相反,為什麼不通過在永久鏈接設置頁面添加另一個字段來向用户提供更改選項的選項?
鈎入 load-options-permalink.php 並設置一些東西來捕捉 $_POST 數據來保存你的 s 。。還要向頁面添加一個設置字段。
<?php
add_action( 'load-options-permalink.php', 'wpse30021_load_permalinks' );
function wpse30021_load_permalinks()
{
if( isset( $_POST['wpse30021_cpt_base'] ) )
{
update_option( 'wpse30021_cpt_base', sanitize_title_with_dashes( $_POST['wpse30021_cpt_base'] ) );
}
// Add a settings field to the permalink page
add_settings_field( 'wpse30021_cpt_base', __( 'CPT Base' ), 'wpse30021_field_callback', 'permalink', 'optional' );
}
然後設置字段的回叫功能:
<?php
function wpse30021_field_callback()
{
$value = get_option( 'wpse30021_cpt_base' );
echo '<input type="text" value="' . esc_attr( $value ) . '" name="wpse30021_cpt_base" id="wpse30021_cpt_base" class="regular-text" />';
}
然後當您註冊您的帖子類型時,用 get_option 抓住 s 子。如果不在,請使用默認值。
<?php
add_action( 'init', 'wpse30021_register_post_type' );
function wpse30021_register_post_type()
{
$slug = get_option( 'wpse30021_cpt_base' );
if( ! $slug ) $slug = 'your-default-slug';
// register your post type, reference $slug for the rewrite
$args['rewrite'] = array( 'slug' => $slug );
// Obviously you probably need more $args than one....
register_post_type( 'wpse30021_pt', $args );
}
這是設置字段部分作為插件 https://gist.github.com/1275867
編輯:另一個選擇
您還可以根據 WPLANG 常數中定義的內容更改段。
只需寫一個保存數據的快速功能…
<?php
function wpse30021_get_slug()
{
// return a default slug
if( ! defined( 'WPLANG' ) || ! WPLANG || 'en_US' == WPLANG ) return 'press';
// array of slug data
$slugs = array(
'fr_FR' => 'presse',
'es_ES' => 'prensa'
// etc.
);
return $slugs[WPLANG];
}
然後得到您註冊您的自定義帖子類型的插槽。
<?php
add_action( 'init', 'wpse30021_register_post_type' );
function wpse30021_register_post_type()
{
$slug = wpse30021_get_slug();
// register your post type, reference $slug for the rewrite
$args['rewrite'] = array( 'slug' => $slug );
// Obviously you probably need more $args than one....
register_post_type( 'wpse30021_pt', $args );
}
最好的選擇,IMO 將是給用户一個選項,並提供堅實的默認值:
<?php
add_action( 'init', 'wpse30021_register_post_type' );
function wpse30021_register_post_type()
{
$slug = get_option( 'wpse30021_cpt_base' );
// They didn't set up an option, get the default
if( ! $slug ) $slug = wpse30021_get_slug();
// register your post type, reference $slug for the rewrite
$args['rewrite'] = array( 'slug' => $slug );
// Obviously you probably need more $args than one....
register_post_type( 'wpse30021_pt', $args );
}
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。