我希望permalinks像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;
}所以它起作用了,给了我一个随机的段塞,但问题是每次我在后端输入帖子时都会改变这个段塞,所以我需要生成它一次,并且是唯一的。
我也找到了这个解决方案
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;
}发布于 2020-03-22 21:38:14
wp_unique_post_slug过滤器的第二个参数是后置id。在第一次创建帖子时,您可以使用它生成一次弹格。
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;
}另一种方法是使用后置元来指示是否生成了弹状体。
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;
}发布于 2020-03-22 23:35:06
好的,我终于找到了解决办法
function append_slug($data) {
global $post_ID;
if (empty($data['post_name'])) {
$n=4;
$data['post_name'] = bin2hex(random_bytes($n));
}
return $data;
}谢谢大家的帮助
https://wordpress.stackexchange.com/questions/361203
复制相似问题