如何为博文自动生成可读的 Permalink

WordPress 默认提供了一个比较适合英语文章的 Permalink 生成机制,如果你跟我一样使用中文标题,那自动生成的 Permalink 中就会包含汉字,这对 URL 而言并不友好。之前我都会手动给每篇博文翻译一个英文标题,再将其 slugify,做得多了就会觉得繁琐,于是我开发了一个 API,可以用来帮助自动化地完成这个过程。

API 的调用方式如下,大家可以免费使用。

GET https://blogkit.apps.gianthard.rocks/api/v1/slugify?t=如何科学饲养母猪

HTTP/2 200 OK
server: nginx
date: Mon, 19 Aug 2024 10:01:06 GMT
content-type: application/json; charset=utf-8
age: 189318
cache-control: public,max-age=31536000
content-length: 24
x-http2-stream-id: 3

"scientific-sow-rearing"

要在 WordPress 中自动调用的话,需要在 WordPress 管理页面添加一些代码:

function suggest_slug_from_api( $slug, $post_id, $post_status, $post_type, $post_parent, $original_slug ) {
    // Only apply for new posts or when the slug is empty
    if ( empty($slug) ) {
        $post = get_post($post_id);
        $title = $post ? $post->post_title : '';

        if ( empty($title) ) {
            return $slug; // Return original slug if no title
        }

        $api_url = 'https://blogkit.apps.gianthard.rocks/api/v1/slugify';

        // Encode the title for use in URL
        $query = http_build_query(array('t' => $title));
        $url = $api_url . '?' . $query;

        // Make the API request
        $response = wp_remote_get($url);

        // Check if the request was successful
        if ( !is_wp_error($response) && wp_remote_retrieve_response_code($response) == 200 ) {
            $body = wp_remote_retrieve_body($response);
            $suggested_slug = json_decode($body, true);

            // If we got a valid slug, use it
            if ( $suggested_slug && is_string($suggested_slug) ) {
                return $suggested_slug;
            }
        }
    }

    // If anything goes wrong or if the post already has a custom slug, return the original slug
    return $slug;
}
add_filter( 'wp_unique_post_slug', 'suggest_slug_from_api', 10, 6 );

我使用的是 WP Code 插件,用这个插件管理 PHP 代码片段非常方便,免费版也很够用。

注意只在 Admin 页面上启用这个片段

上面的代码工作完成后,WordPress 就会在草稿保存后自动生成 URL slug 。需要注意的是,编辑页面的前端可能不会及时更新 URL slug 预览,但是发布后就会使用通过 API 生成的 URL Slug。

评论

《 “如何为博文自动生成可读的 Permalink” 》 有 2 条评论

  1. OP 的头像

    谢谢分享~ 我一般都是直接丢给ChatGPT让他根据标题生成一个slug

    1. Zeeko 的头像

      我的这个 API 背后就是 AIGC ~

回复 Zeeko 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注