对于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);
returnnew_slug;
} else {
return slug;
}
}
# From: https://stackoverflow.com
function so_custmoer_unique_post_slug(col,table='wp_posts'){
globalwpdb;
// 一些在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 uniquealready_exists = (boolean) wpdb->get_var("SELECT COUNT(col) as the_amount FROM table WHEREcol = 'guid'");
} while ( true ==already_exists );
return $guid;
}
主要是利用了wordpress
的内置函数wp_unique_post_slug
来做文章。在wordpress
尝试自动生成别名时,我们自定义了它,的时候会生成一个12位长度的随机字符串,作为这篇文章的别名,而且再你再次编辑,或者把文章变成草稿,编辑之后再发布,不会再生成新的slug
,避免同一篇文章多次生成。
说一句,使用这种随机字符串作为url
对SEO
不是很友好,慎重采用。
wordpress文章使用随机字符串作为url中的slug
原文链接:https://beltxman.com/2929.html,若无特殊说明本站内容为 行星带 原创,未经同意禁止转载。