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

如何在WordPress后台WooCommerce产品页右侧侧边栏添加小工具或PHP代码

在WooCommerce产品编辑后台右侧侧边栏添加自定义内容的方法

方法一:用PHP代码注册自定义Metabox(推荐)

后台产品编辑页的右侧侧边栏模块本质是WordPress的Metabox,通过PHP代码可直接注册并自定义内容,支持嵌入任意PHP逻辑。

步骤1:添加注册与渲染代码

将以下代码添加到主题的functions.php文件(建议用子主题,避免主题更新丢失代码),或自定义插件中:

// 注册产品编辑页右侧侧边栏的自定义Metabox
add_action('add_meta_boxes', 'custom_product_sidebar_metabox');
function custom_product_sidebar_metabox() {
    add_meta_box(
        'custom-product-sidebar', // 唯一ID
        '我的自定义侧边模块', // 模块标题
        'render_custom_product_sidebar', // 内容渲染函数
        'product', // 针对产品类型
        'side', // 位置:右侧侧边栏
        'default' // 显示优先级
    );
}

// 渲染Metabox内容(可嵌入任意PHP逻辑)
function render_custom_product_sidebar($post) {
    // 可选:添加安全验证nonce
    wp_nonce_field('custom_product_sidebar_nonce', 'sidebar_nonce');

    // 示例1:显示静态文本
    echo '<p>这是自定义侧边模块的内容</p>';

    // 示例2:嵌入PHP逻辑,显示当前产品库存状态
    $stock_status = get_post_meta($post->ID, '_stock_status', true);
    echo '<p><strong>库存状态:</strong>' . ucfirst($stock_status) . '</p>';

    // 示例3:添加可输入的表单字段(如需保存数据,需配合保存函数)
    $custom_note = get_post_meta($post->ID, '_custom_product_note', true);
    echo '<p><label for="custom-note">产品备注:</label></p>';
    echo '<textarea id="custom-note" name="custom_note" style="width:100%;height:80px;">' . esc_textarea($custom_note) . '</textarea>';
}

// 可选:保存Metabox中的表单数据
add_action('save_post_product', 'save_custom_product_sidebar_data');
function save_custom_product_sidebar_data($post_id) {
    // 验证权限与安全
    if (!isset($_POST['sidebar_nonce']) || !wp_verify_nonce($_POST['sidebar_nonce'], 'custom_product_sidebar_nonce')) {
        return;
    }
    if (DOING_AUTOSAVE) return;
    if (!current_user_can('edit_product', $post_id)) return;

    // 保存输入的备注
    if (isset($_POST['custom_note'])) {
        update_post_meta($post_id, '_custom_product_note', sanitize_textarea_field($_POST['custom_note']));
    }
}

步骤2:生效验证

添加代码后刷新产品编辑后台页面,右侧侧边栏会出现名为「我的自定义侧边模块」的新模块,包含你定义的内容与PHP逻辑。

方法二:用可视化插件创建(无需写代码)

如果不想编写PHP代码,可使用ACF(Advanced Custom Fields)插件快速实现:

  • 安装并激活ACF插件
  • 创建新字段组,设置「位置」为「产品」→「等于」→「所有产品」
  • 在「显示选项」中,将「位置」选择为「侧边栏」
  • 添加所需字段(如文本框、文本域等),保存字段组后,产品编辑页右侧会自动生成对应模块

注意事项

  • 修改主题文件前务必备份,使用子主题可避免主题更新导致代码丢失
  • 涉及数据保存时,必须添加nonce验证和权限检查,保障后台安全
  • 若仅需显示静态内容或执行PHP逻辑,可删除保存数据的代码部分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:45:22