wordpress函数title()应用替换优化 wordpress



我们要在WordPress主题根据不同的页面动态生成文章标题,需要使用函数wp_title()函数,今天我们来系统记录学习如何更好的使用它来优化我们的页面,更利于seo.

1、函数原型

<?php wp_title( $sep, $echo, $seplocation ); ?>
<title><?php wp_title('&laquo;', true, 'right'); ?> <?php bloginfo('name'); ?></title>

2、参数

$sep

(字符串)(可选)显示在文章标题前后的文字信息(如分隔符)。默认情况下(若分隔符被设为空),那么文章标题前后(由seplocation参数决定)会显示 & raquo; (»)符号。

默认值:

& raquo; (»)

$echo

(布尔型)(可选)回应标题(True),或以PHP字符串形式返回标题(False)。

默认值:True

1 (True) ——默认值

0 (False)

$seplocation

(字符串)(可选)引入于WordPress 2.5,该参数决定sep字符串相对于文章标题的位置。除“right”外的所有值都会将sep放在文章标题前(左侧)。如果seplocation的值为'right',那么sep字符串会显示在文章标题后。

默认值:None

3、用法举例 

在functions.php中,可以这样改造封装


实例一

首页 header.php 调用

<title><?php wp_title(''); ?></title>
在 functions.php 加入
add_filter( 'wp_title', 'wpdocs_hack_wp_title_for_home' );
/**
 * Customize the title for the home page, if one is not set.
 *
 * @param string $title The original title.
 * @return string The title to use.
 */
function wpdocs_hack_wp_title_for_home( $title )
{
  if ( empty( $title ) && ( is_home() || is_front_page() ) ) {
    $title = __( 'Home', 'textdomain' ) . ' | ' . get_bloginfo( 'description' );
  }
  return $title;
}


实例二

首页 header.php

<title><?php wp_title('|', true, 'right'); ?></title>
在 functions.php 加入
/**
 * Creates a nicely formatted and more specific title element text
 * for output in head of document, based on current view.
 *
 * @param string $title Default title text for current view.
 * @param string $sep   Optional separator.
 * @return string Filtered title.
 */
function wpdocs_filter_wp_title( $title, $sep ) {
    global $paged, $page;
    if ( is_feed() )
        return $title
    // 添加网站名称
    $title .= get_bloginfo( 'name' )
    // 为首页添加网站描述 home/front page.
    $site_description = get_bloginfo( 'description', 'display' );
    if ( $site_description && ( is_home() || is_front_page() ) )
        $title = "$title $sep $site_description"
    // 在页面标题中添加页码
    if ( $paged >= 2 || $page >= 2 )
        $title = "$title $sep " . sprintf( __( 'Page %s', 'twentytwelve' ), max( $paged, $page ) ) 
    return $title;
}
add_filter( 'wp_title', 'wpdocs_filter_wp_title', 10, 2 );


PS

WordPress开发团队,已经声明在未来,WordPress4.0以上,会对API升级,让用户让用户选择的文档标题,下面是给出一个对wp_title()函数改进的方向:

if ( ! function_exists( '_wp_render_title_tag' ) ) :
    function theme_slug_render_title() {
?>
<title><?php wp_title( '-', true, 'right' ); ?></title>
<?php
    }
    add_action( 'wp_head', 'theme_slug_render_title' );
endif;


签名:这个人很懒,什么也没有留下!
最新回复 (0)
返回