Creating A WordPress Blog Slug Part 2 – Python

In a previous post, I posted a sample NodeJS function to assemble a WordPress blog slug. I ended up rewriting part of the larger application (and the function itself) in Python.

In the below function, source is a blog title string, and it returns a slug suitable for use in a blog URL.

def generate_slug(source):
    i = 0
    source = source.lower().strip()
    allowed = "abcdefghijklmnopqrstuvwxyz1234567890"
    slug = ""
    while i < (len(source) - 0):
        single_letter = source[i:i+1]
        if single_letter in allowed:
            slug += single_letter
        elif not slug.endswith("-"):
            #letter is not allowed
            #check that the slug doesn't already end in a dash
            slug += "-"
        i = i + 1
    return slug

Creating A WordPress Blog Slug – NodeJS

A slug in WordPress is the part of the URL that references the blog title. For example, if the URL looks like example.com/2019/this-is-my-test-post, then this-is-my-test-post would be a slug. Typically a slug is all letters and numbers, with any other character being replaced by a dash.

The below code fragment is a simple JS function to reduce a blog title down to a slug – you may want to add some additional code to guarantee a certain slug length.


var generateSlug = function generateSlug(title) {
  var allowable_characters = "abcdefghijklmnopqrstuvwxyz1234567890";
  
  //Builds our own slug
  title = title.trim().toLowerCase();
  var title_array = title.split("");
  
  var outbound_title = " ";
  for ( var i = 0; i < title_array.length; i++) {
    var title_char = title_array[i];
    if ( allowable_characters.indexOf(title_char) != -1 ) {
      outbound_title = outbound_title + title_char;
    }
    else if ( outbound_title.split("").pop() != "-" ) {
      outbound_title = outbound_title + "-";
    }
  }
  
  console.log("Generated slug: " + outbound_title);
  
  return outbound_title.trim();
  
}//end generateSlug