Wordpress 4.4.0+ 自定义页面 title 标签的方法

Spoony 54.4m2023-08-10319 次点击
4.4.0版本前,使用wp_title()是很普遍的。而4.1.0引入了title-tag,可以使用
```
function theme_slug_setup() {‌
add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'theme_slug_setup' );
```
来加入theme支持。

4.4.0版本开始,加入了wp_get_document_title()这个函数,而wp_title已经deprecated不推荐使用。

在header.php中,
```
<title><?php echo wp_get_document_title(); ?></title>
```
在functions.php里,添加如下代码:
```
<?php
function custom_document_title_separator()
{‌
$separator = ' | ';
return $separator;
}
add_filter('document_title_separator', 'custom_document_title_separator');

function reform_page_title($title)
{‌
$title['tagline'] = 'Site description when on home page.';
$title['page'] = 'Page number if paginated.';
$title['site'] = 'Site title when not on home page.';
return $title;
}
add_filter('document_title_parts', 'reform_page_title', 10, 1);
?>
```
以上代码中custom_document_title_separator用于添加自定义的分隔符号,reform_page_title是调用document_title_parts这个hook的时候,我们可以对已经生成的title进行二次修改。所以如果不使用这个hook,也是完全没有问题的。

这样一来,页面的title就都已经生成好了!

注意:
如果使用了Yoast SEO这个插件,那么我们需要在激活插件后在functions.php中添加以下代码(WPSEO (~3+) and WordPress (4.4+))来阻止title被重写:
```
function disableYoastTitleRewrite() {‌
if (class_exists('WPSEO_Frontend') {‌
$wpseo_front = WPSEO_Frontend::get_instance();

remove_filter( 'pre_get_document_title', array( $wpseo_front, 'title' ), 15 );
remove_filter( 'wp_title', array( $wpseo_front, 'title' ), 15 );
}
}
add_action( 'init', 'disableYoastTitleRewrite');
```
收藏 ♥ 感谢
暂无回复

登录注册 后可回复。



GitHub