I would like to check from the user interface if a slug url already exists.
I naturally turned to an AJAX solution like this.
`jQuery("#slugBrut").keyup(function() {
var slugBrutText = jQuery("#slugBrut").val() ;
jQuery.ajax({
type:"POST",
url: "theme/is_valid_slug.php",
data:{
slug : slugBrutText
},
success: function(result){
console.log(result);
}});
});`
And on the called script side is_valid_slug.php
, it looks like this
`<?php
require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
global $wpdb;
$slug = $_POST['slug'] ;
$post_if = $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_name like '$slug'");
echo $post_if ; // returns 0 or 1`
Everything works fine. However, I am not a wordpress pro and I would like to know if this way of doing things is dangerous and if another approach would be better?
CodePudding user response:
if you are coding in custom plugin or theme (any files in wp-content) No need to require wp-load.php . if you want better way for create ajax in WP fallow this AJAX wordpress document
NOTE : you can write callback in functions.php in your theme directory or child theme .
NOTE 2 : Also you can use this wp function Instead SQL query.
$exists = get_page_by_path( $slug, OBJECT, $post_type );
return (int) $exists; // 1 or 0