Verifying WordPress slug existence using AJAX

I want to verify if a slug URL already exists using the user interface. My initial idea was to use an AJAX solution similar to 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);
        }});
    });`

In the script is_valid_slug.php that is being called, it is structured as follows:

`<?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`

While everything seems to be functioning correctly, since I am not well-versed in WordPress development, I am curious to know whether this method poses any security risks and if there could be a more optimal approach?

Answer №1

When coding in a custom plugin or theme (any files in wp-content), there is no need to require wp-load.php. For a better way to create ajax in WordPress, follow this AJAX wordpress document

Note: You can write callbacks in functions.php in your theme directory or child theme.

Note 2: You can also use the WordPress function instead of SQL queries.

$exists = get_page_by_path( $slug, OBJECT, $post_type );
 return (int) $exists; // 1 or 0

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing the Date Display with AJAX Response

Within a view, there is a DisplayFor connected to a DateTime field in the Model. After an AJAX call returns a Date to update the field, I am able to convert the AJAX date into a MM/DD/YYYY format. However, using .val to set the DisplayFor does not reflect ...

Failure to trigger the success action in ExtJS

I am currently utilizing struts2 for the server-side implementation combined with ExtJS4 for the user interface. I have a basic form that I submit to the server, but the response consistently goes to the failure case of the request even though I am just re ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

Steps to refresh my View following an Ajax Post request

Working in an MVC environment, I find myself calling a Controller method from my View. The Controller method conducts some validation checks and then returns to the same view with a faulty modelstate. However, despite expecting all of my validation fields ...

Tips for making an AJAX request using jQuery

I have a new project that involves collecting user data and displaying it on the same page. I was able to successfully implement an Ajax call using JavaScript, but now I want to transition to using jQuery. Below is my JavaScript code: var output1 = docum ...

What is the process for generating a new object through an Ajax call?

Let's say I have my main view displaying all the items stored in the database. Instead of manually clicking on a Create button, I want to utilize Ajax to add new items without refreshing the page. How can this be achieved? What changes should be made ...

The jQuery OnClick function fails to work in Internet Explorer when a user tries to execute a "ctrl+click"

One of my jQuery functions triggers an ajax POST when a link (href) with a specific id is clicked. It works perfectly fine in Chrome - I can simply click the link or use "Ctrl" + "Click" to open it in a new tab, and the ajax POST executes as intended. Howe ...

The functionality of Jquery AJAX is operational, however, the message being displayed appears to

Inside the file changename.php, there is a DIV element: <div id="resultDiv"></div> Within the same file, PHP code can be found: <?php include_once ('connect.php'); if(isset($_POST['name'])) { $postedname = $_POST[&ap ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Performing jQuery Ajax Request with multiple Form Elements

I have created multiple forms using my php code, as demonstrated below. My issue is that when I try to make a jquery-ajax request, I'm not sure how to reference a specific form. My objective is for the relevant form data to be posted when the submit ...

Expanding the SimpleModal container size

I recently implemented the SimpleModal plugin on my website. However, I encountered an issue with resizing the modal dialog box. Specifically, after clicking 'Yes' on a confirm dialog, the modal becomes small. The other challenge I am facing is ...

Assorted presentation of list items in HTML tags

I am working on creating a poll and I was wondering if there is a way to display the questions randomly each time the page is visited. I'm thinking of storing the questions in a PHP or JavaScript array. Can anyone recommend a good tutorial that can he ...

Tips for altering an element's style attribute using ERB and JQuery while including a % symbol within the value

I'm attempting to adjust the style="width: 5%" attribute of a span using Jquery and AJAX. This width needs to be specified in percentage as it represents a progress bar. Here is my code snippet from html.erb: <div class="progress success round" ...

Open the HTML document and access the file contents

I'm having trouble reading a text file from my computer onto a website. It works fine in Internet Explorer, but won't work in Chrome. I don't have much experience with HTML, so any help would be much appreciated! <html> <body> ...

Execute an Angular factory AJAX request with each change in route

I operate a factory where I utilize a function called getExpenseList that performs an ajax call to fetch data from the expense table. Currently, I have two routes set up - one for listing expenses and another for adding new expenses. However, whenever I n ...

The Ajax data is appearing in the console, however, it is not being recognized as a valid PHP value

Hey there, I have a question about utilizing Ajax. I've searched for similar issues but can't seem to find anything that matches my problem. Below is the code in question: $(document).ready(function() { $("#nume").blur(function() { numeform = ...

Leveraging the power of jquery-tmpl with the responseText

I am currently working on populating jquery-templates retrieved through an ajax call from a different folder on the server. I attempted to fill the responseTexts using .tmpl({..}) but unfortunately, it didn't work as expected. Here is my approach: va ...

Trigger the original function again once the other function completes in jQuery AJAX

I'm working on improving my skills in jQuery, AJAX, and JSON. Within my application, there is a dropdown select menu: <select id="serviceload" name="serviceload"></select> The OPTIONS in the select menu are populated dynamically by anot ...

Is there a more efficient method for validating the values of an AJAX request?

I am currently working on developing an AJAX backend for a Django application and I'm not sure if I'm approaching it the right way. Currently, in order to accept integer values, I find myself having to typecast them using int(), which often leads ...

Tips on extracting information from an AJAX call using JQuery

My current project involves utilizing a webapi in asp.net that outputs JSON data. I am looking to integrate this webapi with JQuery within a php-created website. The following is the JQuery code I am using to retrieve information from the webapi: $.ajax( ...