当您手动注册自定义文章类型时,WordPress 允许您设置一个独特的存档别名。您的配置方式将决定该别名是否会被翻译成您的次要语言。
在手动注册自定义文章类型时,您可以使用 has_archive 函数设置一个独特的存档别名。
WPML 允许将 has_archive 设置为字符串。然而,如果字符串值被设置为 rewrite['slug'], 以外的其他内容,或者未设置自定义文章类型名称别名,则存档别名将不可翻译。
设置可翻译的别名
在这个代码示例中,我们设置了
'has_archive' => true。假设别名 book 已被翻译为西班牙语的 libro,则存档链接如下:
- 英语(默认语言):http://mydomain.tld/book/
- 西班牙语(次要语言):http://mydomain.tld/es/libro/
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'book',
array(
'labels' => array(
'name' => __( 'Books', 'textdomain' ),
'singular_name' => __( 'Book', 'textdomain' )
),
'public' => true,
'has_archive' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => 'book'),
'supports' => array('title','editor', 'custom-fields','thumbnail')
)
);
}
在默认语言和次要语言中设置相同的别名
在这个代码示例中,我们为参数'has_archive' => 'my-books' 设置了一个特定的字符串。现在存档链接如下:
- 英语(默认语言):http://mydomain.tld/my-books/
- 西班牙语(次要语言):http://mydomain.tld/es/my-books/
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'book',
array(
'labels' => array(
'name' => __( 'Books', 'textdomain' ),
'singular_name' => __( 'Book', 'textdomain' )
),
'public' => true,
'has_archive' => 'my-books', // Do not use the gettext functions for this parameter
'publicly_queryable' => true,
'exclude_from_search' => false,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => 'book'),
'supports' => array('title','editor', 'custom-fields','thumbnail')
)
);
}
自定义别名的故障排除
某些主题和插件允许网站管理员为其自定义文章类型和自定义分类法设置自定义别名。
如果您翻译后的自定义别名返回 404 错误,请检查以下内容:
- 在所有请求中(每种语言、前端、后台、AJAX、heartbeat 等),自定义类型应始终使用相同的别名进行注册。因此在
'rewrite' => [ 'slug' => $my_custom_slug ],中,$my_custom_slug的值不应在不同请求之间发生变化,即使它来自某个选项(或任何自定义设置)。 - WPML 仅支持自定义别名翻译(在注册自定义类型时),但不支持自定义固定链接结构。
- 如果自定义别名作为选项存储,则不应在
wpml-config.xml文件中将其注册为admin-texts。 - 在更新自定义别名的值后,主题/插件还应刷新重写规则(通过调用
flush_rewrite_rules();)。