自定义 WordPress 前台语言标签

很多同学都使用英文版的 WordPress,那么,这就造成了前台的 html 标签的 lang 属性错误,可能会影响搜索引擎或广告平台机器人对您网页的抓取。

<html dir="ltr" lang="en-US">

这是若您使用英文 WordPress 得到的默认效果。

我刚刚写完一个 Frontend Language Customizer for WordPress 插件,希望可以帮到您。又是一个代码比说明还短的插件,不过它很有用。要知道,乱改主题代码是不好的哦。请在 WordPress 目录新建目录和文件 /wp-content/plugins/frontend-language-customizer/frontend-language-customizer.php,代码如下:

(代码已更新,可通过 W3C Validator 的测试)

<?php
/*
Plugin Name: Frontend Language Customizer
Plugin URI: http://jiehan.org/tech/customize-your-wordpress-frontend-language-tag/
Description: Enables you to set your site language tags which shows up in frontend.
Author: Jiehan Zheng
Version: 0.1
Author URI: http://jiehan.org/
*/
 
define("YOUR_DESIRED_DIR", "ltr");      // 您想要的书写方向
define("YOUR_DESIRED_LANG", "zh-CN");   // 您想要的语言定义
 
function flc_replace_tag($original_output) {
        return preg_replace('/lang=".*?"/', 'lang="' . YOUR_DESIRED_LANG . '"',
                preg_replace('/dir=".*?"/', 'dir="' . YOUR_DESIRED_DIR . '"', $original_output)
        );
}
 
add_filter('language_attributes', 'flc_replace_tag');
?>

我就不发到 WordPress.org 插件目录了,因为这个插件几年内应该不会有不会再有更新。有问题请随时留言反馈。