Introduction
I have always had a bit of an obsession: when looking at WordPress posts, if the post_name field is not set, it will default to using the title title as the post_name, which results in Chinese characters appearing when post_name is used as the post URL. It looks quite inconsistent.
However, I do not want to set post_name manually, so I wondered whether post_name could be set to the same value as the ID by default.
Batch Replacement of Existing Data
First, replace all already published posts using an SQL statement directly:
UPDATE wp_posts SET post_name = ID;
Here, wp_posts is the posts table in the WordPress database.
Automatically Modify When Publishing Posts
To set post_name to the same value as the ID by default whenever a post is published or updated in WordPress, this can be achieved by adding a custom function.
Open the functions.php file in the WordPress theme folder and add the following code at the end of the file:
function set_postname_as_id( $post_id ) {
$post = get_post( $post_id );
$post_name = $post->post_name;
$post_id = $post->ID;
if ( $post_name != $post_id ) {
$args = array(
'ID' => $post_id,
'post_name' => $post_id,
);
wp_update_post( $args );
}
}
add_action( 'save_post', 'set_postname_as_id' );
Save and upload the functions.php file to your WordPress theme folder.
Whenever a post is published or updated, WordPress will check whether the post's post_name is the same as its ID. If they are different, it will automatically update post_name to the ID. Note that this will affect all types of posts, including pages and custom post types. If you only want to apply this to specific types of posts, you can add an appropriate conditional check inside the set_postname_as_id function.
For example, I use the B2 theme and want to replace all post types except page pages. It can be changed as follows:
function set_postname_as_id( $post_id ) {
// 获取文章对象
$post = get_post( $post_id );
// 获取当前文章的 post_name 和 ID
$post_name = $post->post_name;
$post_id = $post->ID;
// 检查文章类型是否为 page,如果是则返回
if ( $post->post_type == 'page' ) {
return;
}
// 检查 post_name 是否与 ID 不同
if ( $post_name != $post_id ) {
// 准备要更新的文章参数
$args = array(
'ID' => $post_id,
'post_name' => $post_id,
);
// 更新文章的 post_name 为 ID
wp_update_post( $args );
}
}
// 在保存文章时触发自定义功能
add_action( 'save_post', 'set_postname_as_id' );