首页 > 解决方案 > 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 调用列表中看到它:

xhr 调用

谢谢!

标签: javascriptwordpress

解决方案


在这里这里找到了解决方案。

我修改了排队的脚本以使用依赖项“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;
            } );
    }
});

推荐阅读