Products
GG网络技术分享 2025-03-18 16:12 1
有时我们在定制一些比较特别的需求的时候,需要获取分类的ID,以满足特别的需要,下面列举一下获取分类ID的方法。
如果是分类页面,系统默认有个变量$cat,就是分类的ID,但是只能在分类页面使用
在page页面使用
主题中使用自定义字段显示
直接循环使用
get_the_category的返回值为二维数组
cat_ID – 分类 ID ,
cat_name – 分类名 ,
category_nicename – 别名 ,
category_description – 分类描述 ,
category_parent – 父分类 ID ,
category_count – 包含文章数量。
在wordpress网站中默认生成的链接会含有中文,不太友好,对搜索引擎也不好,如果手动去设置又会显得比较麻烦。
第一种方法是安装自动转换的插件:PinYin Slug
直接在后台上传安装就可以了。
第二种方法,需要在主题函数functions.php中加入功能函数:
1.百度翻译的代码
//自动生成英文别名-百度版functionbymt_slug_auto_translate($title){
$wp_http_get=wp_safe_remote_get('https://fanyi.baidu.com/v2transapi?from=zh&to=en&transtype=trans&query='.$title);
if(emptyempty($wp_http_get->errors)){
if(!emptyempty($wp_http_get['body'])){
$trans_result=json_decode($wp_http_get['body'],true);
$trans_title=$trans_result['trans_result']['data'][0]['dst'];
return$trans_title;
}
}
return;
}
add_filter('sanitize_title','bymt_slug_auto_translate',1);
2.微软翻译的代码
//自动生成英文别名-微软版functionbymt_slug_auto_translate($title){
$wp_http_get=wp_safe_remote_get('https://api.microsofttranslator.com/v2/ajax.svc/TranslateArray2?appId=%22TKT68kjRgkUbVtIKst6Vo0Hxnb6g2f0K3tUMyn1gZ7nc*%22&from="zh"&to="en"&options={}&texts=["'.$title.'"]');
if(emptyempty($wp_http_get->errors)){
if(!emptyempty($wp_http_get['body'])){
preg_match('/"TranslatedText":"([^"]+)/i',$wp_http_get['body'],$trans_result);
$trans_title=$trans_result[1];
return$trans_title;
}
}
return;
}
大家可以根据自己网站的需要进行选择,这样就可以自动生成,不需要每次都自己手动来添加别名了。
Demand feedback