WordPress 中文标题无法显示日期问题

问题:wordpress使用中文标题时候回显示如下图问题,包含中文标题的文章无法正常显示日期,但不包含中文的标题中中能正常显示日期。

image-20200416145041895

思路:只要文章标题不包含中文即可,那么用文章ID作为文章的别名。

修改过程

老文章批量修改

将下面代码放到wp-config.php文件最低部,保存好后重新打开一次网站,如果网站文章比较多,这里需要等待网页刷出的时间就长。网页加载完后即得删除刚刚添加的代码

/**
 * 批量更改旧文章的别名为ID
 * 使用方法:将代码添加到网站根目录的 wp-config.php 的最底部,访问一次网站首页,等页面打开后,再删除这些代码
 * https://www.wpdaxue.com/wordpress-using-post-id-as-slug.html
 */
// 添加一个变量来包容文章标题数组,防止重复操作
$slug_done = array();
// 查询所有文章
$posts = $wpdb->get_results( "
	SELECT
	`ID`,
	`post_title`
	FROM
	`" . $wpdb->posts . "`
	WHERE
	`post_type` = 'post'
	" );
// 输出文章
foreach( $posts AS $single ) {
	$this_slug = $single->ID;
	$slug_done[] = $this_slug;
    //  使用文章ID替换文章原来的别名
	$wpdb->query( "
		UPDATE
		`" . $wpdb->posts . "`
		SET
		`post_name` = '" . $this_slug . "'
		WHERE
		`ID` = '" . $single->ID . "'
		LIMIT 1
		" );
}

微信图片_20200416143516

新文章自动修改

将下面代码放到主题的functions.php文档末尾,新添加的文章就会自动使用ID作为别名

/**
 * 新文章自动使用ID作为别名
 * 作用:即使你设置固定连接结构为 %postname% ,仍旧自动生成 ID 结构的链接
 * https://www.wpdaxue.com/wordpress-using-post-id-as-slug.html
 */
add_action( 'save_post', 'using_id_as_slug', 10, 2 );
function using_id_as_slug($post_id, $post){
	global $post_type;
	if($post_type=='post'){ //只对文章生效
		// 如果是文章的版本,不生效
		if (wp_is_post_revision($post_id))
			return false;
		// 取消挂载该函数,防止无限循环
		remove_action('save_post', 'using_id_as_slug' );
		// 使用文章ID作为文章的别名
		wp_update_post(array('ID' => $post_id, 'post_name' => $post_id ));
		// 重新挂载该函数
		add_action('save_post', 'using_id_as_slug' );
	}
}

微信图片_20200416143851

效果展示

是不是正常显示很舒服

image-20200416151021679

参考链接

http://www.loonblog.com/2020/04/16/261/ https://www.wpdaxue.com/wordpress-using-post-id-as-slug.html

发表评论