我希望永久链接像youtube一样,由9位数的字母和数字生成我修改了这个代码
add_filter( \'wp_unique_post_slug\', \'unique_slug_108286\', 10, 4 );
function unique_slug_108286( $slug) {
$n=4;
$slug = bin2hex(random_bytes($n)); //just an example
return $slug;
}
所以它是有效的,并给了我一个随机的slug,但问题是每次我在后端进入帖子时,这个slug都会发生变化,所以我需要它被生成一次并且是唯一的
我也找到了这个解决方案,它也起作用了,但同样的问题,每次我进入帖子都会改变
add_filter( \'wp_unique_post_slug\', \'unique_slug_so_11762070\', 10, 6 );
function unique_slug_so_11762070( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
$new_slug = so_11762070_unique_post_slug(\'guid\');
return $new_slug;
}
# From: https://stackoverflow.com/a/11762698
function so_11762070_unique_post_slug($col,$table=\'wp_posts\'){
global $wpdb;
$alphabet = array_merge( range(0, 9), range(\'a\',\'z\') );
$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;
}
SO网友:Shazzad
的第二个参数wp_unique_post_slug
过滤器是post id。在第一次创建post时,您只能利用它生成一次slug。
Method 1:
add_filter( \'wp_unique_post_slug\', \'unique_slug_108286\', 10, 2 );
function unique_slug_108286( $slug, $postId ) {
if ( ! $postId ) {
$n = 4;
$slug = bin2hex( random_bytes( $n ) ); //just an example
}
return $slug;
}
另一种方法是使用post-meta来指示是否生成了slug
Method 2:
add_filter( \'wp_unique_post_slug\', \'unique_slug_108286\', 10, 2 );
function unique_slug_108286( $slug, $postId ) {
if ( $postId && ! get_post_meta( $postId, \'slug_generated\', true ) ) {
$n = 4;
$slug = bin2hex( random_bytes( $n ) ); //just an example
update_post_meta( $postId, \'slug_generated\', true );
}
return $slug;
}