问题描述
在 wordpress 安装中,我有一个自定义帖子类型和一个带有自定义 post_Meta 字段的元框。
Gutenberg 侧边栏中的父下拉字段曾经是一个 <select>
元素。我有一些脚本 onChange
触发不同字段的隐藏/显示,使它们成为有条件的,具体取决于正在编辑的页面是父页面还是子页面:
$(document).on("change",".editor-page-attributes__parent select",function(){
toggleFields();
}
<select>
中的选项将 ID 作为值,因此我可以获得所选父级的标题和 ID,并在元框中为我的用户动态显示一些数据:
var dropdown = $('.editor-page-attributes__parent select');
var parentName = dropdown.find(':selected').text();
var parentId = dropdown.val();
自 v5.6 以来,wordpress 已用 Combo Box 替换了该 select 元素。我试图获得相同的数据 onChange
,但使用 blur
只取得了一些成功:
$(document).on("blur",".editor-page-attributes__parent .components-comboBox-control__input",function(){
toggleFields();
var parentName = dropdown.val();
})
我只能获取页面标题,因为此组合框现在有一个缺少 ID 的输入元素,如下所示:
<input id="components-form-token-input-0" type="text" class="components-comboBox-control__input components-form-token-field__input" value="Page Name Here">
我也尝试过使用 Ajax 来使用 get_page_by_title()
检索 ID,但它并不总是有效,因为页面可能具有相同的标题,并且编辑器还在层次结构级别的名称中添加了破折号和空格。
解决方法
阅读 Editor Documentation 一段时间后,我找到了正确的解决方案。这是您如何在 WP 编辑器中收听更改并获取父组合框选择的 ID:
display: flex;
align-items: center;
wp.data.subscribe( function () {
var newParent = wp.data.select('core/editor').getEditedPostAttribute('parent');
console.log(newParent);
} );
每次在编辑器中编辑帖子时当前状态发生更改时都会被调用,因此每次都会调用侦听器函数。当我们想要的字段发生实际更改时,我们可以通过简单的变量检查来避免这种情况。 It behaves as Redux subscribe 没有取消订阅,只有一个听众。
要检查我们正在编辑的当前帖子类型,我们可以使用 getCurrentPostType:
wp.data.subscribe
这是此问题的完整代码以供将来参考:
wp.data.select('core/editor').getCurrentPostType();