WordPress文章别名slug自动生成随机字符串

网站APP 8 个月前 回复

, , ,

对于wordpress,它自带的文章url固定连接可选样式有很多,带日期的,文章名,文章ID,但是自己输入难免麻烦,文章ID已经不合符理想了,现在Wordpress历史版本,ID数字不太好。
但如果想要每一篇文章一个随机字符串的slug(别名,显示在url后面),就要自己动手了,如果你不理解那是怎样的,看看简书的文章详情页的url就知道了。
function.php中加入下面的代码即可:

add_filter( 'wp_unique_post_slug', 'unique_slug_so_customer', 10, 6 );

function unique_slug_so_customer( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
	if($post_type != 'post' || get_post_meta($post_ID,'unique_slug', true) ==1){
		if(!empty($slug)){
			return $slug; 
		}
	};
	add_post_meta($post_ID, 'unique_slug', 1, true);
	$newSlug = auto_unique_post_slug('guid');
	wp_update_post(array('post_name' => $newSlug ));
}

function auto_unique_post_slug($col,$table='wp_posts'){
    //上面的参数wp_posts为自己的表名,如果不是默认,改为自己的
    global $wpdb;

    // WordPress slug 更新后大写会自动转成小写,所以不建议用大写字母
    $str = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $alphabet = str_split($str);

    $already_exists = true;

    do {
        $guidchr = array();
        //下面的参数36为上面 $str 的字符串数量
        for ($i=0; $i<36; $i++)
            $guidchr[] = $alphabet[array_rand( $alphabet )];
        //yl是前缀,可以改成自己的,下面的参数10为生成的字符串位数
        $guid = sprintf( "yl%s", implode("", array_slice($guidchr, 0, 10, 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;

}

参考文章:
https://www.jianshu.com/p/fdc62f68c48e

wordpres使用随机字符串作为网址(固定链接)

更新#2023.12.17

上面这段代码,好像会有一些问题,如果觉得不好用,可以参考下面这段代码,auto_unique_post_slug函数不变,将unique_slug_so_customer函数及其挂钩换成下面这段即可:

add_filter('name_save_pre', function ($slug)
{
    // 检查是否是文章发布操作
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    // 手动编辑时,不自动转换
    if ($slug && $slug !== '') {
        return $slug;
    }

    // 替换文章标题
	$slug = auto_unique_post_slug('guid');
    return $slug;
}, 10, 1);

这段代码的好处就是不用判定更新文章或者已经有slug的文章,而且也不需要添加自定义栏目,减少数据库数据,缺点就是自动保存时生成的slug与发布文章时不同,主要是因为自动保存时生成的slug没有被写入数据库,当被写入数据库后就不会有变化了。
此段代码参考wenprise-pinyin-slug插件

支付宝打赏微信打赏

如果此文对你有帮助,欢迎打赏作者。

发表评论

欢迎回来 (打开)

(必填)