plugin development - How to check category name available or not

admin2025-01-07  3

I have an input field and when users enter any text then that will check the category name is available or not which user entered.

Js

(function($) {  // ready handler
$(".universalSearchField").keypress(function() {
     $.ajax({
        url: "/wp-admin/admin-ajax.php",
        type: "post",
        data: { action: "universalSearchlist", keyword: $("#searchdata").val() },
        success: function(data) {
            console.log(data);
           // $("#datafetch").html( data );
        }
    });
    });

    })(jQuery);

Function.php

 add_action('wp_ajax_universalSearchlist','universalSearch');
 add_action('wp_ajax_nopriv_universalSearchlist','universalSearch');
function universalSearch(){
$the_query = new WP_Query( array('category_name' => esc_attr( $_POST['universalSearchlist'] ), 'post_type' => 'post' ) );
    foreach ( $the_query->posts as $p ) {
    $categories = get_the_category($p->ID);
    if (!empty($categories) ) {
        echo esc_html( $categories[0]->name );   
    }
}
    
}

I am getting all the categories and I want when the user starts to enter the text box then start checking the category name is available or not.

I have an input field and when users enter any text then that will check the category name is available or not which user entered.

Js

(function($) {  // ready handler
$(".universalSearchField").keypress(function() {
     $.ajax({
        url: "/wp-admin/admin-ajax.php",
        type: "post",
        data: { action: "universalSearchlist", keyword: $("#searchdata").val() },
        success: function(data) {
            console.log(data);
           // $("#datafetch").html( data );
        }
    });
    });

    })(jQuery);

Function.php

 add_action('wp_ajax_universalSearchlist','universalSearch');
 add_action('wp_ajax_nopriv_universalSearchlist','universalSearch');
function universalSearch(){
$the_query = new WP_Query( array('category_name' => esc_attr( $_POST['universalSearchlist'] ), 'post_type' => 'post' ) );
    foreach ( $the_query->posts as $p ) {
    $categories = get_the_category($p->ID);
    if (!empty($categories) ) {
        echo esc_html( $categories[0]->name );   
    }
}
    
}

I am getting all the categories and I want when the user starts to enter the text box then start checking the category name is available or not.

Share Improve this question asked Aug 26, 2020 at 13:01 Naren VermaNaren Verma 2491 gold badge6 silver badges19 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

Use get_cat_ID('categoy name') https://developer.wordpress.org/reference/functions/get_cat_id/

<?php
$category_id = get_cat_ID('Category Name');
if($category_id > 0){
echo 'category exists';
}else{
echo 'category NOT exists';
}
?>

Using admin-ajax.php and writing a custom handler is unnecessary, I would normally advise writing a REST API endpoint instead, but even that's unnecessary here.

Just ask the REST API for that category. If it returns the category, it exists, if it doesn't, then it doesn't.

E.g. https://example.com/wp-json/wp/v2/categories/?slug=categoryname

In javascript that might look like this:

async function check_category_exists( slug ) {
    let response = await fetch( `https://example.com/wp-json/wp/v2/categories/?slug=${slug}` );

    if (response.ok) { // if HTTP-status is 200-299
        // get the response body (the method explained below)
        let json = await response.json();
        return ( json.length > 0 );
    } else {
        throw new Exception( "HTTP-Error: " + response.status );
    }
}

Now we have an async JS function that fetches the term and if it's found returns true, and if it does not returns false. Remember these return promises, similar to the AJAX functions in jQuery and elsewhere. You would use it like this:

check_category_exists( "test" ).then(
    ( result ) => {
        if ( result ) {
            console.log( "test exists" );
        } else {
            console.log( "it does not exist" );
        }
    }
).catch(
    error => console.log( "something went wrong" )
);

Be sure to change example.com to your site, or even better, make WP put the path to your REST API on the page so you can access it, and use the same code everywhere ( hint: ask this question on the site, easy to answer, lots of interesting things to know )

Alternatively, fetch the categories from the REST API via /wp-json/wp/v2/categories and store them in an array/list. Then you can use the array to list items in your search, and you can test if an item is in that array to see if it exists.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736252356a39.html

最新回复(0)