Create Slug from Post Title

Create Slug from Post Title

by Adi Jaya

HTML

<div data-type="form">
<p>
  <input
    data-slug="true"
    type="text"
    name="title"
    placeholder="Title"
    id="title"
    autocomplete="off"
  />
</p>

<p>
  <b>Permalink :</b> <span id="view-slug"></span>
</p>

<p>
  <!-- Change the text type with type hidden, if the actual situation [for database] -->
  <input
    type="text"
    name="slug"
    placeholder="slug" id="slug" readonly disabled/>
</p>

<p>
  <textarea 
    rows="8"
    cols="50" 
    name="content"
    placeholder="Post"
    id="article" ><p>Lorem Ipsum...</p></textarea>
</p>

<p>Example : 
  <button data-example="submit">Submit</button>
</p>

</div>

CSS

* {
  box-sizing: border-box;
}

[type="text"] {
  width: 100%;
  padding: 10px;
}

[name="content"] {
  width: 100%;
  padding: 10px;
  resize: vertical;
}

#input-slug-edit {
  display: inline;
  width: auto;
  padding: 0;
}

JavaScript

var $baseURL = "https://example.com/";

/*this for example
function checkSlugURL(){
			$.ajax({
				url: "check-slug.php",
				data:'post_name='+$("[name='slug']").val(),
				type: "POST",
				success:function(data){
					$( '[name="slug"]' ).attr("value",data.replace(/\s+/g, '')).val(data.replace(/\s+/g, ''));
				},
				error:function (){
					
				}
			});
}

//check-slug.php
<?php
define('ACCESS','OPEN');
require 'admin-loader.php';

if (!is_login() && !is_admin()) { 
		// is_login() and is_admin() => function.php
    header('location:login.php');
    exit();
}

if(!empty($_POST["post_name"])) {
	$post_name = mysqli_real_escape_string($db, $_POST['post_name']);
	$sql = "select * from posting where post_name = '$post_name'";
	$process = mysqli_query($db, $sql);
	
	$post_name = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/','-',$post_name)));
	$dateTime = date("Y-m-d-H:i:s");
	$dateTime = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/','-',$dateTime)));
	$num = mysqli_num_rows($process);
	
	if($num == 0){
		echo $post_name;
	}else{
		echo ''.$post_name.'-'.$dateTime.'';
	}
}
?>

*/
function exampleProcessSubmit(){
	var title 			= $('#title').val();
  var slug 				= $('#slug').val();
  var article 		= $('#article').val();
	alert("Title : "+ title +"\nSlug : "+ slug +"\nArticle : "+ article +"");
}



$('#title').change(function() {
	$(this).val( $.trim( $(this).val() ) );
});

$( "#title" ).blur(function(){
	var $val = $( this ).val();
      $val =  $val.toLowerCase();
      $val =  $val.replace(/[^a-zA-Z0-9]+/g,'-');
      
  var $slug = $val;
  if( $( this ).val() != "" ){
			if( $( this ).attr( "data-slug" ) == "true" ){
      
					$("#view-slug").html( "<a id='example-url' target='_blank' href='"+ $baseURL + $slug +"'>"+ $baseURL + $slug +"</a> <button class='edit-slug' data-name='edit'>Edit</button>" );
          
          //test
          //alert( "baseURL : "+ $baseURL +"" );
          //alert( "Exp Slug 1 : "+ $slug +"" );
          //alert( "Exp Slug...