問題描述

在我的主題中,我想定義一系列定製的帖子型別和自定義分類,每個都有自己的定製 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。