WordPress: evitare tassonomie duplicate con jQuery e AJAX

WordPress: evitare tassonomie duplicate con jQuery e AJAX

Con jQuery e AJAX possiamo facilitare il nostro lavoro con le tassonomie personalizzate di WordPress nel backend.

Creiamo la seguente action di verifica:


function my_check_term() {
    $term = trim( $_GET['term'] );
    $output = array();
    $exists = term_exists( $term, 'my-taxonomy' );
    if ( $exists !== 0 && $exists !== null) {
        $output['exists'] = true;
    } else {
        $output['exists'] = false;
    }
    header( 'Content-Type: application/json' );
    echo json_encode( $output );
    exit();
}

add_action( 'wp_ajax_my_check_term', 'my_check_term' );

Quindi con jQuery modifichiamo la stringa del termine scelto durante l'inserimento:


$( ".my-term" ).each(function() {
    var $input = $( this );

    $input.on( "blur", function() {
        var term = $input.val();
        var url = location.protocol + "//" + location.host + "/wp-admin/admin-ajax.php";
        var data = {
            action: "my_check_term",
            term: term
        };
        
        $.when( $.get( url, data ) ).done(function( resp ) {
            if( resp.exists ) {
                $input.val( term + "-2" );
            }

        });

    });
});

Torna su