新主題的WordPress固定鏈接格式是:/%category%/%post_id%.html(分類(lèi)名/文章ID.html)
但是我有的分類(lèi)下有很多子分類(lèi),那么文章鏈接就會(huì)變成:http://m.keai-mm.cn/父分類(lèi)/子分類(lèi)/文章ID.html
這樣的話鏈接目錄層次就有點(diǎn)深,從某種方面來(lái)講不太利于SEO優(yōu)化,然后就要想辦法干掉WordPress固定鏈接中的子分類(lèi)了,把下面的代碼添加到WordPress主題中的functions.php里面:
[php]// wordpress 去掉固定鏈接中的子分類(lèi)http://m.keai-mm.cn/theme/blog/2294.html
//去掉后: http://m.keai-mm.cn/theme/2294.html
add_filter('post_link','custom_post_type_link',10,3);
function custom_post_type_link($permalink, $post, $leavename) {
if (!gettype($post) == 'post') {
return $permalink;}
switch ($post->post_type) {
case 'post':
//$permalink = get_home_url() . '/' . $post->post_name . '/';
$cats = get_the_category($post->ID);
$subcats = array();
foreach( $cats as $cat ) {
$cat = get_category($cat->term_id);
//if($cat->parent) { $subcats[] = sanitize_title($cat->name);
if($cat->parent) { $subcats[] = $cat->slug;}}
if($subcats) {
foreach($subcats as $subcat) {
$subcat = $subcat.'/';
$permalink = str_replace($subcat, "", $permalink);}}
break;}
return $permalink;} [/php]
多級(jí)分類(lèi)解決方法:
[php]// wordpress 去掉固定鏈接中的所有子分類(lèi)包含孫分類(lèi)http://m.keai-mm.cn/theme/blog/ceshi/2294.html
//去掉后: http://m.keai-mm.cn/theme/2294.html
function remove_child_categories_from_permalinks( $category ) {
while ( $category->parent ) {
$category = get_term( $category->parent, 'category' );
}
return $category;
}
add_filter( 'post_link_category', 'remove_child_categories_from_permalinks' );[/php]
新主題官方微信公眾號(hào)
掃碼關(guān)注新主題(XinTheme)官方公眾號(hào),本站動(dòng)態(tài)早知道。
發(fā)布本站最新動(dòng)態(tài)(新主題發(fā)布、主題更新)和WordPress相關(guān)技術(shù)文章。