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

如何在WordPress中关联submit_button()与wp_insert_post()?

我来帮你搞定这个问题!你的代码里按钮和生成文章的函数之间没有建立关联,所以点击按钮根本不会触发函数执行。咱们一步步来修复:

问题分析

你现在的代码只是单独渲染了一个按钮,也写了生成文章的函数,但两者没有任何联动——按钮点击后没有触发对programmatically_create_post()的调用,自然不会生成文章。

完整解决方案

咱们需要给按钮加上表单提交逻辑,同时处理后台的请求验证和函数触发,以下是可直接使用的代码示例(可以放到你的主题functions.php里,或者自定义插件中):

// 添加后台菜单页面(如果还没有的话)
add_action('admin_menu', 'create_post_button_page');
function create_post_button_page() {
    add_menu_page(
        '生成文章工具', // 页面标题
        '生成文章', // 菜单标题
        'publish_posts', // 权限要求(需要能发布文章的权限)
        'create-post-tool', // 菜单slug
        'render_create_post_button' // 渲染页面的函数
    );
}

// 渲染带按钮的页面
function render_create_post_button() {
    // 处理按钮提交请求
    if (isset($_POST['generate_post'])) {
        // 验证请求合法性,防止CSRF攻击
        check_admin_referer('generate_post_nonce');
        // 检查用户权限
        if (!current_user_can('publish_posts')) {
            wp_die('你没有权限执行此操作!');
        }
        
        // 调用生成文章的函数
        $post_id = programmatically_create_post();
        
        // 提示操作结果
        if (is_wp_error($post_id)) {
            echo '<div class="notice notice-error"><p>生成文章失败:' . $post_id->get_error_message() . '</p></div>';
        } else {
            echo '<div class="notice notice-success"><p>文章生成成功!<a href="' . get_edit_post_link($post_id) . '" target="_blank">点击编辑</a></p></div>';
        }
    }

    // 渲染表单和按钮
    ?>
    <div class="wrap">
        <h1>一键生成文章</h1>
        <form method="post">
            <?php
            // 添加nonce字段用于验证
            wp_nonce_field('generate_post_nonce');
            // 渲染提交按钮
            submit_button('生成新文章', 'primary', 'generate_post');
            ?>
        </form>
    </div>
    <?php
}

// 生成文章的函数(优化下post_author参数,应该用用户ID而不是用户名)
function programmatically_create_post() {
    // 先通过用户名获取用户ID,避免直接写用户名的问题
    $user = get_user_by('login', 'steve');
    if (!$user) {
        return new WP_Error('invalid_user', '找不到用户steve');
    }

    return wp_insert_post(array(
        'comment_status' => 'closed',
        'ping_status' => 'closed',
        'post_author' => $user->ID, // 这里用用户ID更可靠
        'post_title' => 'bronco',
        'post_type' => 'post',
        'post_status' => 'publish' // 可以加上发布状态,默认是draft,根据需求调整
    ));
}
关键说明
  • 表单与请求验证:用<form>包裹按钮,加上wp_nonce_field和check_admin_referer是为了防止跨站请求伪造(CSRF),这是WordPress后台开发的标准安全做法。
  • 权限检查:current_user_can('publish_posts')确保只有有权限发布文章的用户才能触发这个操作。
  • post_author参数优化:原来的代码直接写用户名steve,换成通过get_user_by获取用户ID更可靠,避免用户名变更导致的错误。
  • 状态提示:处理wp_insert_post的返回值,给用户显示成功或失败的提示,提升体验。

把这段代码添加到你的主题functions.php或者自定义插件后,刷新后台就能看到“生成文章”的菜单,点击按钮就能自动创建文章啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:35:26