在Wordpress中自定义Post Slug的自动生成

Bib*_*ath 5 php wordpress

当我们在wordpress中添加新帖子时,在提供帖子标题后,会自动生成slug.我需要编辑该自动生成模块,以便我可以自动在slug的末尾添加一些任意数字.怎么做?

Jak*_*ake 13

不要使用OP在此处使用的硬编码版本.当他这样做时,没有可用的过滤器.最近,自3.3以来,增加了一个过滤器.

add_filter( 'wp_unique_post_slug', 'custom_unique_post_slug', 10, 4 );
function custom_unique_post_slug( $slug, $post_ID, $post_status, $post_type ) {
    if ( $custom_post_type == $post_type ) {
        $slug = md5( time() );
    }
    return $slug;
}
Run Code Online (Sandbox Code Playgroud)

然而,这种方法将在每次保存帖子时改变slu .. ...这是我希望的...

编辑:

这种工作只限制一代.唯一的缺点是,在创建标题后ajax运行时会创建一个版本,然后在保存帖子时创建另一个永久性slug.

function custom_unique_post_slug( $slug, $post_ID, $post_status, $post_type ) {
    if ( $custom_post_type == $post_type ) {
        $post = get_post($post_ID);
        if ( empty($post->post_name) || $slug != $post->post_name ) {
            $slug = md5( time() );
        }
    }
    return $slug;
}
Run Code Online (Sandbox Code Playgroud)