【Polylang】カスタム投稿タイプのラベルを文字列翻訳で切り替える方法

WordPressの多言語化プラグイン【Polylang】でカスタム投稿のラベル(タイトル部分)がそのままだと上手く翻訳対応できなかったので、方法を調べてみました。
文字列翻訳へ入力項目を作る
Polylangのメニューにある【文字列翻訳】の機能を使用します。
function.phpに以下のコードを入力すると文字列翻訳に項目が表示されます・
例はカスタム投稿(ニュース)を追加した場合を想定。
カスタム投稿と書いている部分は任意の文字列で大丈夫。(文字列翻訳の一覧に表示される)
///カスタム投稿(イベント)の多言語化
add_action(‘init’, function() {
pll_register_string(‘カスタム投稿’, ‘ニュース’);
});
カスタム投稿タイプのコードを修正
手書きかCustom Post Types UIとかで吐き出したカスタム投稿しようするためのコードをfunctions.phpに記載。
labelの部分をpll__()で囲めば先ほどのコードと連動する形で文字列翻訳で調整できるようになります。
add_action( ‘init’, ‘cptui_register_my_cpts’ );
function cptui_register_my_cpts() {
$labels = array(
“name” => __( pll__(‘ニュース’)),
“singular_name” => __( pll__(‘ニュース’) ),
);
$args = array(
“labels” => $labels,
“description” => “”,
“public” => true,
“publicly_queryable” => true,
“show_ui” => true,
“delete_with_user” => false,
“show_in_rest” => true,
“rest_base” => “”,
“rest_controller_class” => “WP_REST_Posts_Controller”,
“has_archive” => true,
“show_in_menu” => true,
“show_in_nav_menus” => true,
“exclude_from_search” => false,
“capability_type” => “post”,
“map_meta_cap” => true,
“hierarchical” => false,
“rewrite” => array( “slug” => “news”, “with_front” => false ),
“query_var” => true,
“supports” => array( “title”, “editor” ),
);
register_post_type( “news”, $args );
// End of cptui_register_my_cpts()
}
まとめ
ちょっと情報を探すのに時間がかかったけど、やってみたらかなりスッキリした感じでできたので満足。
多言語サイトはちょっとのことでつまずきそうなので他にも手間取ったりしたところは記事にしていく予定です。