Synchronize WordPress Post post_name with the ID

8,712 3

Preface

I have always had a bit of an obsession: when I see that an article in WordPress has a post_name field, if it is not set, it will default to using the title title as post_name, which causes Chinese characters to appear when post_name is used as the article URL. It looks rather awkward.

However, I do not want to set post_name manually, so I wondered whether it could be set to the same value as the ID by default.

Batch Replacement of Existing Data

First, replace all already-published articles using a SQL statement:

SQL
UPDATE wp_posts SET post_name = ID;

Here, wp_posts is the article table in the WordPress database.

Automatically Modify When Publishing Articles

To set post_name to the same value as the ID by default whenever an article is published or updated in WordPress, you can add a custom function to achieve this.

Open the functions.php file in your WordPress theme folder and add the following code at the end of the file:

PHP
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 an article is published or updated, WordPress will check whether the article's post_name is the same as its ID. If they are different, it will automatically update post_name to the ID. Please note that this will affect all types of articles, including pages and custom post types. If you only want to apply it to specific types of articles, 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. It can be changed as follows:

PHP
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' );

Comments

(3)
  1. 随遇而安
    Chrome 104 Windows 7

    你好,看你的站做的挺不错的,空了联系下我1587894193,想和你商量下广告事宜。

  2. don
    Edge 118 Windows 10

    您好,想注册img的图床,不过似乎无法刷新出验证码

  3. Edge 119 Windows 10

    小俊博客的域名已更改,烦请博主更改一下,谢谢!

Leave a comment