在 Wordpress 中自定义 Post Slug 的自动生成 [英] Customize the auto generation of Post Slug in Wordpress

查看:35
本文介绍了在 Wordpress 中自定义 Post Slug 的自动生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When we add new post in wordpress, after supplying the post title, the slug is generated automatically. I need to edit that auto generation module so that i can add some arbitrary number in the end of the slug automatically. How to do it?

推荐答案

不要使用 OP 在这里使用的硬编码版本.当他这样做时,没有可用的过滤器.最近,从 3.3 开始,添加了一个过滤器.

Don't use the hard-coded version that the OP used here. When he did that, there was not a filter available. More recently, since 3.3, a filter was added.

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;
}

但是,每次保存帖子时,此方法都会更改 slug...这正是我所希望的...

However this method will change the slug every time you save the post... Which was what I was hoping for...

这种将生成限制为一次的作品.唯一的缺点是它会在创建标题后运行 ajax 时创建一个版本,然后在保存帖子时创建另一个永久的 slug.

This kind of works for limiting the generation to just once. The only drawback is that it creates one version when ajax runs after creating the title, then it creates another, permanent slug when the post is saved.

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;
}

这篇关于在 Wordpress 中自定义 Post Slug 的自动生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆