Se dobbiamo effettuare delle operazioni AJAX sui post singoli di WordPress, ottenere l'ID del post si rivela fondamentale.
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:
'use strict';
const getTheID = () => {
const body = document.body;
if(!body.classList.contains('single')) {
return '';
}
const bodyClass = body.className;
const pattern = /postid-(\d+)/;
if(!pattern.test(bodyClass)) {
return '';
}
const idMatch = bodyClass.match(pattern);
return idMatch[1];
};