2

I want to have a custom permalink for each new post in WordPress like: http://mysite.com/x5Kvy6 (like bit.ly).

I tried this little script, but it adds only 5-digit numbers to the post title in the permalink.

function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {

if($slug!=""){
  $random=rand(11111,99999); //I needed 5 digit random
  $slug .= "-" . $random;
}
return $slug;

}

How can I make a random key instead of the post title?

I have not researched URL shorteners or redirection methods.

Any idea is welcome!

4

4 回答 4

3
function wp_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;
}

这可以通过多种方式进行优化。

同样关于这一点wp_unique_post_slug()- yikes 注意名称间距。Wordpress 已经使用了这个函数名

于 2012-08-01T15:35:53.407 回答
1
if($slug!=""){
   $random=rand(11111,99999); //I needed 5 digit random
   $slug = $random;
}

.= 用于字符串的连接。

于 2012-08-01T15:05:25.550 回答
1

使用Mwayi 答案的正确方法是使用 filter wp_unique_post_slug,这function wp_unique_post_slug()将与 WP 自己的功能相冲突。在 WP 函数中,我们找到了这个过滤钩子。

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;
}
于 2017-05-07T12:34:41.230 回答
0

对于 SEO,你最好让 slug 尽可能有意义,即。不要将永久链接更改为随机序列。使用此插件,您仍然可以使用http://example.com/raNd0m永久链接在社交网络或您网站上的图像中共享目的。

这样您就可以同时赢得SEO短链接


我用http://ijassar.info/underrated写了一篇关于这个特定主题的帖子

于 2014-10-22T13:36:27.030 回答