AI编程生活评测

wordpress文章使用随机字符串作为url中的slug

编程笔记 / 2019-12-06 / 2 min
对于 wordpress ,它自带的文章 url 固定连接可选样式有很多,带日期的,文章名,文章ID,但如果想要每一篇文章一个随机字符串的 slug (别名,显示在 url 后面),就要自己动手了,如果你不理解那是怎样的,看看简书的文章详情页的 url 就知道了。 主题的 function.php 中加入下面的代码即可:
add_filter( 'wp_unique_post_slug', 'unique_slug_so_custmoer', 10, 6 );

function unique_slug_so_custmoer( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
    $real_status = get_post_status($post_ID); 
    if ($post_type == 'post' && in_array( $real_status, array( 'draft', 'pending', 'auto-draft' )) && empty(get_post_meta($post_ID,'unique_slug', true))) {
        $new_slug = so_custmoer_unique_post_slug('guid');
        add_post_meta($post_ID, 'unique_slug', 1, true);
        return $new_slug;
    } else {
        return $slug;
    }
}

# From: https://stackoverflow.com
function so_custmoer_unique_post_slug($col,$table='wp_posts'){
    global $wpdb;

    // 一些在url中不好看的字符比如pqjyil0,在这里去除了
    $str = 'abcdefhkmnorstuvwwxz2345678923456789234567892345678923456789';
    $alphabet = str_split($str);

    $already_exists = true;

    do {
        $guidchr = array();
        for ($i=0; $i<32; $i++)
            $guidchr[] = $alphabet[array_rand( $alphabet )];
        $guid = sprintf( "%s", implode("", array_slice($guidchr, 0, 12, true)) );
        // check that GUID is unique
        $already_exists = (boolean) $wpdb->get_var("SELECT COUNT($col) as the_amount FROM $table WHERE $col = '$guid'");
    } while ( true == $already_exists );

    return $guid;

}
主要是利用了 wordpress 的内置函数 wp_unique_post_slug 来做文章。在 wordpress 尝试自动生成别名时,我们自定义了它,的时候会生成一个12位长度的随机字符串,作为这篇文章的别名,而且再你再次编辑,或者把文章变成草稿,编辑之后再发布,不会再生成新的 slug ,避免同一篇文章多次生成。 说一句,使用这种随机字符串作为 urlSEO 不是很友好,慎重采用。