Se dobbiamo effettuare delle operazioni AJAX sui post singoli di WordPress, ottenere l'ID del post si rivela fondamentale. A volte l'ID è già disponibile tramite la funzione the_ID()
, ma qualora non lo fosse dobbiamo utilizzare un approccio diverso.
Data la seguente marcatura generata dalla funzione body_class()
:
<body class="single single-post postid-12345 single-format-standard">
possiamo definire la seguente funzione di utility:
(function( $ ) {
$.getTheID = function() {
var id = "";
if( $( "body" ).hasClass( "single" ) ) {
var bodyClass = $( "body" ).attr( "class" );
var idMatch = bodyClass.match( /postid-\d+/ );
id = idMatch[0].replace( "postid-", "" );
}
return id;
}
})( jQuery );
Esempio d'uso:
$(function() {
var id = $.getTheID();
$.ajax({
type: "GET",
dataType: "text",
url: "http://" + location.host + "/wp-admin/admin-ajax.php",
data: {
postid: id,
action: "my_count_visits"
},
success: $.noop
});
});