预计阅读时间: 6 分钟

最近的几个项目都开始用WPML,一边做一边查询官方文档和论坛,提炼出一些实用函数,记录在此。

获得当前页面的language Code


echo ICL_LANGUAGE_CODE; //这个变量直接输出当前页面语言编码,比如默认的英语就是“en”,法语就是“fr”

获取指定页面ID和language code修正后的ID
WPML的保存机制是为每个语言单独生成一篇文章,因此要调用特定语言的文章,只要知道它对应其他任何一个语种的一篇文章的ID就可以用这个函数输出:


icl_object_id(ID, type, return_original_if_missing,language_code);

icl_object_id的官方文档:http://wpml.org/documentation/support/creating-multilingual-wordpress-themes/language-dependent-ids/

获取指定页面的permalink
由于受到language code的影响,WordPress默认的permalink可能会给出404错误,这是一个解决方案:


function get_permalink_current_language( $post_id ){
	$language = ICL_LANGUAGE_CODE;
	$lang_post_id = icl_object_id( $post_id , 'hotel', true, $language );
	$url = "";
	if($lang_post_id != 0) {
		$url = get_permalink( $lang_post_id );
	}else {
		//如果找不到就返回对应当前语言的首页
		global $sitepress;
		$url = $sitepress->language_url( $language );
	}
	return $url;
}

通过文章ID查询对应的语言
这个函数利用$wpdb查询出任何一篇文章所对应的language code,很实用!


function get_langcode_post_id($post_id){
	global $wpdb;
	$query = $wpdb->prepare('SELECT language_code FROM ' . $wpdb->prefix . 'icl_translations WHERE element_id="%d"', $post_id);
	$query_exec = $wpdb->get_row($query);
	return $query_exec->language_code;
}

有了以上函数,就能正确的实现带language code的伪静态了


add_filter('post_type_link', 'custom_hotel_link', 1, 3);
function custom_hotel_link( $link, $post = 0 ){
	if ( $post->post_type == 'hotel' ){//以hotel文章类型为例
		return home_url( 'hotels/' . $post->ID .'.html?lang='.get_langcode_post_id($post->ID) );
	}else {
		return $link;
	}
}
add_action( 'init', 'custom_hotel_rewrites_init' );
function custom_hotel_rewrites_init(){
	add_rewrite_rule(
		'hotels/([0-9]+)?.html$',
		'index.php?post_type=hotel&p=$matches[1]',
		'top' );
}

进行非当前语言的查询


global $sitepress;
//存储当前语言到变量$current_lang
$current_lang = $sitepress->get_current_language();
//切换语言到英语
$sitepress->switch_lang("en");
 
$myposts = get_posts( array( 
	'numberposts'=>9999,
	'post_type' => 'hotel', 
	'orderby' => 'title',
	'order' => 'ASC',
	'suppress_filters' => 0
) );
foreach( $myposts as $post ) {
	......
}
wp_reset_postdata();
 
//切换回当前页面语言
$sitepress->switch_lang($current_lang);
此文章对你有帮助吗? 已有 1 人说这篇文章是有用的。