首页>文档>源码技巧>Wordpress>WordPress文章固定链接显示随机别名

此组别内的文章

需要支持?

如果通过文档没办法解决您的问题,请提交工单获取我们的支持!

WordPress文章固定链接显示随机别名

WordPress文章固定链接显示随机别名,说一句,使用这种随机字符串作为 url 对 SEO 不是很友好,慎重采用。

有需要的可以加以下代码加入您使用的WordPress主题中的functions.php文件中:

/*WordPress文章固定链接显示随机别名 dzcrv.com*/
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 ) {
    $real_status = get_post_status($post_ID); 
    if ($post_type == 'post' && empty(get_post_meta($post_ID,'unique_slug', true))) {
        $new_slug = so_customer_unique_post_slug('guid');
        add_post_meta($post_ID, 'unique_slug', 1, true);
        return $new_slug;
    } else {
        return $slug;
    }
}
# 随机别名
function so_customer_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( "thax%s", implode("", array_slice($guidchr, 0, 8, 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 ,避免同一篇文章多次生成。

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索