Random permalink key in wordpress

末鹿安然 提交于 2019-12-04 17:05:03
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;
}

This can be optimised in a number of ways.

Also regarding this wp_unique_post_slug() -- yikes watch out for the name spacing. Wordpress already uses this function name

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

.= is for concat of strings.

brasofilo

The correct way to use Mwayi answer is using the filter wp_unique_post_slug, as function wp_unique_post_slug() will conflit with WP own function. Inside WP function we find this filter hook.

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;
}

For SEO, you better keep the slug as meaningful as possible, ie. do not change the permalink to a random sequence. Using This plugin, you still can use http://example.com/raNd0m permalink for sharing purposes in social networks or images from your site.

This way you win both SEO and shortlinks


I used http://ijassar.info/underrated to write a post about this specific subject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!