javascript - WP帖子更新时执行js
问题描述
我正在尝试在更新(或创建)WordPress 帖子后执行 JavaScript 工作,并在 js 中使用刚刚更新的帖子的数据(我需要将它们发送到某些 API)。到目前为止,我知道我必须将脚本排入 wp-admin 的 edit.php:
函数.php
function wpdocs_selectively_enqueue_admin_script( $hook ) {
if ( 'edit.php' != $hook ) {
return;
}
wp_enqueue_script( 'tha_adminjobs', get_template_directory_uri(). '/js-fanky/adminjobs.js', array(), '1.0' );
}
add_action( 'admin_enqueue_scripts', 'wpdocs_selectively_enqueue_admin_script' );
现在我可以对更新按钮单击执行操作:
js-fanky/adminjobs.js
jQuery(document).on("click", ".editor-post-publish-button", function(){
console.log("hi");
});
但是我如何访问数据?我可以看到它们从 post.php?post={someid} 返回 - 我在 XHR 调用列表中看到它:
谢谢!
解决方案
我修改了排队的脚本以使用依赖项“wp-api-fetch”
function wpdocs_selectively_enqueue_admin_script( $hook ) {
if ( $hook != 'post.php' && $hook !='post-new.php' ) { //fixed wrong url here too
return;
}
wp_enqueue_script( 'tha_adminjobs', get_template_directory_uri(). '/js-fanky/adminjobs.js', , array( 'wp-api-fetch' ), '1.0' );
}
add_action( 'admin_enqueue_scripts', 'wpdocs_selectively_enqueue_admin_script' );
然后我使用“中间件”从 wp rest api 获取 JSON,这在问题的屏幕截图中。它会在使用 JSON 填充管理表单字段之前立即获取它。
var apiFetch=null;
$(document).on("click", ".editor-post-publish-button", function(){
if(apiFetch==null){ //the listener is not set yet. Setting it after the first publish click, otherwise it would fire also on editor load
var apiFetch=wp.apiFetch;
apiFetch.use( ( options, next ) => {
const result = next( options );
result.then( () => {
if(result._v.status=="publish"){ //to get only the post, not other api answers
//play with result JSON here
console.log(result._v);
}
} );
return result;
} );
}
});
推荐阅读
- c++ - CMake 和/或在向项目添加提升时出错
- javascript - 为多个项目设置通用 Storybook.js
- angular - 异步管道和 ngFor 不显示项目
- javascript - 箭头功能不起作用,但使用旧方法的功能有效
- spring - 服务端启动后如何初始化dataSource、transactionManager配置bean?
- angular - 无法在 Angular 的 GET 请求中显示在 Chrome [object Object] 中
- javascript - 警告后我的计算器没有响应
- c# - 如何将 xpath 声明为字符串变量?C#
- python - Python 库是否特定于操作系统
- html - 在弹出窗口上禁用滚动条