-
In WP's general settings, we enabled commenting for posts by default. For any reason (maybe bug, maybe user misbehavior) commenting is disabled for some posts after publishing. Therefore, I implemented a plain JS event listener which checks the current discussion settings when the editor clicks on "Publish". // file my-block-editor-js.js
function isCommentsEnabledInBlockEditor() {
// Retrieve comments checkbox by it's label text (German)
const xpath = "//label[text()='Kommentare erlauben']";
const matchElem = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (matchElem) {
const id = matchElem.getAttribute("for");
if (id) {
return document.getElementById(id).checked;
}
}
}
function registerPublishBtnHandler() {
const publishBtnArray = document.getElementsByClassName("editor-post-publish-button__button");
if (publishBtnArray && publishBtnArray.length > 0) {
const publishBtn = publishBtnArray[0];
if (publishBtn) {
publishBtn.addEventListener("click", function (e) {
if (!isCommentsEnabledInBlockEditor()) {
if (!confirm("Comments are disabled. Still publish?")) {
e.preventDefault();
e.stopPropagation();
}
}
});
}
}
}
window.addEventListener('load', function () {
registerPublishBtnHandler();
}); This doesn't work anymore with WordPress current version 6.6.1 as there is no "Allow commenting" checkbox anymore. Obviously, it would be better to use the WordPress JavaScript API. I search in the repo and did quite a lot of research on the web but didn't find anything helpful. So my question is: how to access and update current post's discussion settings via API? Disclaimer: there's an unanswered question on stackexchange regarding this issue. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
10 minutes after asking the question I found it out 🙂 You can access current comment status via wp.data.select('core/editor').getEditedPostAttribute('comment_status') So the current solution is: // file my-block-editor-js.js
function isCommentsEnabledInBlockEditor() {
return wp.data.select('core/editor').getEditedPostAttribute('comment_status') === 'open';
}
function registerPublishBtnHandler() {
const publishBtnArray = document.getElementsByClassName("editor-post-publish-button__button");
if (publishBtnArray && publishBtnArray.length > 0) {
const publishBtn = publishBtnArray[0];
if (publishBtn) {
publishBtn.addEventListener("click", function (e) {
if (!isCommentsEnabledInBlockEditor()) {
if (!confirm("Comments are disabled. Still publish?")) {
e.preventDefault();
e.stopPropagation();
}
}
});
}
}
}
window.addEventListener('load', function () {
registerPublishBtnHandler();
}); Still it's not optimal to use a plain JS click handler to listen for publish ... but at least I got one step further. |
Beta Was this translation helpful? Give feedback.
10 minutes after asking the question I found it out 🙂
You can access current comment status via
So the current solution is: