You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

后台点击按钮调用functions.php中PHP函数的实现问题

实现WordPress后台自定义按钮调用PDF生成函数

要实现点击新增的「Update PDF」按钮单独调用mysave函数,需要通过AJAX请求完成(直接点击链接会刷新页面,无法触发后台函数且会干扰原更新按钮功能),具体步骤如下:

1. 修改按钮输出,添加安全验证与交互逻辑

更新update_my_data函数,给按钮添加安全标识(nonce)和文章ID,同时嵌入JS处理点击事件:

add_action( 'edit_form_after_title', 'update_my_data');
function update_my_data( $post ) {
    if( 'item' !== $post->post_type ) return;

    // 生成安全验证nonce
    $nonce = wp_create_nonce( 'generate_pdf_nonce_' . $post->ID );
    ?>
    <a href="#" class="button-primary generate-pdf-btn" data-post-id="<?php echo $post->ID; ?>" data-nonce="<?php echo $nonce; ?>">Update PDF</a>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const pdfBtn = document.querySelector('.generate-pdf-btn');
            if(!pdfBtn) return;

            pdfBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const postId = this.dataset.postId;
                const nonce = this.dataset.nonce;

                // 发送AJAX请求
                fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'generate_pdf',
                        post_id: postId,
                        nonce: nonce
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if(data.success) {
                        alert('PDF生成成功!');
                        // 可选:刷新页面或更新页面提示
                    } else {
                        alert('PDF生成失败:' + data.message);
                    }
                })
                .catch(error => {
                    console.error('请求出错:', error);
                    alert('请求失败,请重试');
                });
            });
        });
    </script>
    <?php
}

2. 注册AJAX处理动作

在functions.php中添加AJAX请求的处理函数,负责验证权限和调用PDF生成逻辑:

// 注册后台AJAX动作(仅登录用户可访问)
add_action('wp_ajax_generate_pdf', 'handle_generate_pdf');

function handle_generate_pdf() {
    // 验证nonce
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $nonce = isset($_POST['nonce']) ? sanitize_text_field($_POST['nonce']) : '';

    if(!wp_verify_nonce($nonce, 'generate_pdf_nonce_' . $post_id)) {
        wp_send_json_error(['message' => '安全验证失败']);
    }

    // 验证用户权限(确保当前用户可编辑该文章)
    if(!current_user_can('edit_post', $post_id)) {
        wp_send_json_error(['message' => '无操作权限']);
    }

    // 获取文章对象
    $post = get_post($post_id);
    if(!$post || $post->post_type !== 'item') {
        wp_send_json_error(['message' => '无效的文章类型']);
    }

    // 调用PDF生成函数
    mysave($post_id, $post);

    // 返回成功响应
    wp_send_json_success(['message' => 'PDF生成完成']);
}

3. 调整mysave函数适配单独调用

原mysave函数的逻辑基本可以保留,移除自动保存相关的检查(因为是手动触发),并优化元数据获取的容错性:

function mysave($id, $post) 
{
    if ($post->post_type != 'item'){
        return;
    }

    if (wp_is_post_revision($id)) {
        return;
    }

    if (wp_is_post_autosave($id)) {
        return;
    }
    
    if ( 'trash' === $post->post_status ) {
        return;
    }

    if ( 'draft' === $post->post_status ) {
        return;
    }

    $dig = get_post_meta($id, 'wpcf-digitisation-project-no')[0] ?? '';
    $inv = get_post_meta($id, 'wpcf-inventory-no')[0] ?? '';
    
    if( !empty($dig) ){
        $command = escapeshellcmd('python3 '. dirname(__FILE__). '/create_pdf.py digital '.$inv);
    }else{
        $command = escapeshellcmd('python3 '. dirname(__FILE__). '/create_pdf.py hl'.$inv);
    }
    
    exec( $command, $output, $ret_code);   
}

关键注意事项

  • 安全验证:必须添加nonce和权限检查,防止恶意请求。
  • 路径问题:确保create_pdf.py的路径正确,dirname(__FILE__)指向functions.php所在目录,若脚本在其他位置需调整路径。
  • 错误处理:可在exec后根据$ret_code判断Python脚本是否执行成功,返回更精准的提示。

内容的提问来源于stack exchange,提问作者Martha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:36:17