提取WooCommerce我的账户各板块短代码问题求助
解决WooCommerce「我的账户」各板块短代码提取问题
你的代码仅对orders板块生效,原因是WooCommerce不同账户板块的渲染逻辑并不统一:只有订单这类带endpoint的板块会触发woocommerce_account_{$section}_endpoint钩子,仪表盘、账户详情等板块依赖其他钩子或模板渲染,登出则是生成安全链接的逻辑。
以下是修复后的完整代码,支持你需要的所有板块:
add_shortcode('my_account_section', 'shortcode_my_account_section'); function shortcode_my_account_section($atts) { // 验证用户是否登录,未登录则返回提示 if (!is_user_logged_in()) { return '<p>请先登录以查看账户内容。</p>'; } $atts = shortcode_atts([ 'section' => '' ], $atts); $section = sanitize_text_field($atts['section']); ob_start(); switch ($section) { case 'dashboard': // 渲染仪表盘内容 do_action('woocommerce_account_dashboard'); break; case 'orders': // 渲染订单列表 do_action('woocommerce_account_orders_endpoint'); break; case 'addresses': // 加载地址模板,包含账单和收货地址 wc_get_template('myaccount/addresses.php'); break; case 'account-details': // 渲染账户详情编辑表单 do_action('woocommerce_account_edit_account'); break; case 'logout': // 生成安全登出链接 $logout_url = wp_logout_url(get_permalink(wc_get_page_id('myaccount'))); echo '<a href="' . esc_url($logout_url) . '">登出账户</a>'; break; default: // 默认返回仪表盘内容 do_action('woocommerce_account_dashboard'); break; } return ob_get_clean(); }
各板块短代码使用示例:
- 仪表盘:
[my_account_section section="dashboard"] - 订单:
[my_account_section section="orders"] - 地址:
[my_account_section section="addresses"] - 账户详情:
[my_account_section section="account-details"] - 登出:
[my_account_section section="logout"]
代码说明:
- 登录检查:确保未登录用户无法访问账户内容,符合WooCommerce的权限逻辑
- 仪表盘:调用官方指定的
woocommerce_account_dashboard钩子,渲染原生仪表盘内容 - 地址:直接加载WooCommerce内置的
addresses.php模板,保证地址编辑表单、账单/收货地址展示完整 - 账户详情:通过
woocommerce_account_edit_account钩子渲染账户信息编辑表单 - 登出:生成带安全nonce的登出链接,避免直接跳转的安全风险
内容的提问来源于stack exchange,提问作者Kambro
相关产品推荐
相关产品推荐

