我有一个名为"short_title“的ACF自定义字段,我想要基于这个字段而不是post标题字段的post的段塞。
我已经写了这段代码:
function testSlug($post_id)
{
if (get_post_type($post_id) == 'my-custom-post-type') {
if (defined('DOING_AUTOSAVE' && DOING_AUTOSAVE)) {
return;
}
if (!current_user_can('edit_post', $post_id)) {
return;
}
remove_action('save_post', 'testSlug');
$updated_post = [];
$updated_post['ID'] = $post_id;
$updated_post['post_name'] = sanitize_title($_POST['acf']['field_61f8bacf53dc5']);
wp_update_post($updated_post);
add_action('save_post', 'testSlug');
clean_post_cache($post_id);
}
}
add_action('save_post', 'testSlug');
这很好,可以编辑弹格,但在编辑器上,弹格字段与此字段不同步,当我们单击“保存”或“发布”按钮时,弹格字段将填充post标题段塞。
但是,如果我们刷新编辑页面,就会显示正确的片段。
我尝试做一些JS来同步ACF字段的输入事件和段塞字段,但是它不起作用,因为当面板关闭时,元素将从DOM中删除。此外,即使面板在页面加载时打开,脚本也会在编辑器未完全加载时运行得太早,并且返回undefined
,因为字段有一个动态ID (inspector-text-control-X
,X
为1,2,.)。
如何将弹格字段与自定义字段同步?如何防止post标题字段中的事件编辑弹格字段?
发布于 2022-05-02 12:20:18
我找到了一种方法来动态地改变短标题自定义字段的弹格字段。
jQuery(document).ready(() => {
const acfField = 'field_61f8bacf53dc5';
const inputShortTitle = document.getElementById('acf-' + acfField);
const slugify = (str) => {
return str.toLowerCase().replace(/ /g, '-')
.replace(/-+/g, '-').replace(/[^\w-]+/g, '');
}
const updateSlug = () => {
wp.data.dispatch('core/editor').editPost({slug: slugify(inputShortTitle.value)});
}
if (inputShortTitle !== null) {
inputShortTitle.addEventListener('input', () => updateSlug());
}
});
wp.data.dispatch('core/editor').editPost({slug: 'my-slug-value-here'});
是可以更改Gutenberg弹域组件的命令。不再需要PHP,因为当我按Save按钮时,脚本所填充的实际值被发送到API。
https://wordpress.stackexchange.com/questions/405250
复制相似问题