您现在的位置是:首页 > 网站制作 > WordpressWordpress

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

杰帅2023-06-26【Wordpress】人已围观

简介为了文章更好的被搜索引擎收录,有时需要WordPress主题根据不同的页面动态生成文章标题,这时要使用函数wp_title()函数,优化我们的页面,更利于seo。

为了文章更好的被搜索引擎收录,有时需要WordPress主题根据不同的页面动态生成文章标题,这时要使用函数wp_title()函数,优化我们的页面,更利于seo。

函数原型

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

参数

$sep
(字符串)(可选)显示在文章标题前后的文字信息(如分隔符)。默认情况下(若分隔符被设为空),那么文章标题前后(由seplocation参数决定)会显示 & raquo; (»)符号。
默认值:
& raquo; (»)
$echo
(布尔型)(可选)回应标题(True),或以PHP字符串形式返回标题(False)。
默认值:True
1 (True) ——默认值
0 (False)
$seplocation
(字符串)(可选)引入于WordPress 2.5,该参数决定sep字符串相对于文章标题的位置。除“right”外的所有值都会将sep放在文章标题前(左侧)。如果seplocation的值为'right',那么sep字符串会显示在文章标题后。
默认值:None

用法举例

在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 );

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;

如果你对wp_title的改进升级感兴趣,可以查看官方开发文档:
https://make.wordpress.org/core/2015/10/20/document-title-in-4-4/

Tags:wordpress函数   wordpress教程   wp_title()函数

很赞哦! ()

文章评论

本站推荐

站点信息

  • 建站时间:2018-10-24
  • 网站程序:帝国CMS7.5
  • 主题模板《今夕何夕》
  • 文章统计1172篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们