如何为WooCommerce我的账户添加自定义标签及端点?代码返回404错误
解决WooCommerce我的账户自定义端点404问题
问题原因
原代码仅添加了查询变量,但未完成端点注册、菜单添加这两个关键步骤,同时缺少固定链接刷新操作,导致访问时返回404。
完整修复代码
// 1. 注册自定义端点 add_action( 'init', 'register_myaccount_custom_endpoint' ); function register_myaccount_custom_endpoint() { // 注册端点,设置访问权限为用户登录可见 add_rewrite_endpoint( 'custom-endpoint', EP_ROOT | EP_PAGES ); } // 2. 添加查询变量 add_filter( 'woocommerce_get_query_vars', 'myaccount_custom_endpoint_query_var' ); function myaccount_custom_endpoint_query_var( $query_vars ) { $query_vars['custom-endpoint'] = 'custom-endpoint'; return $query_vars; } // 3. 添加自定义菜单项到我的账户菜单(带图标) add_filter( 'woocommerce_account_menu_items', 'add_custom_endpoint_to_myaccount_menu' ); function add_custom_endpoint_to_myaccount_menu( $items ) { // 在订单菜单项后插入自定义选项,可调整插入位置 $new_items = array(); foreach ( $items as $key => $label ) { $new_items[$key] = $label; if ( 'orders' === $key ) { // 这里用Font Awesome图标,可替换为主题自带图标类或文本符号 $new_items['custom-endpoint'] = '<i class="fas fa-star"></i> ' . __( 'Endpoint Label', 'text-domain' ); } } return $new_items; } // 4. 输出自定义端点内容 add_action( 'woocommerce_account_custom-endpoint_endpoint', 'display_custom_endpoint_content' ); function display_custom_endpoint_content() { echo '<p>' . __( 'Hello! 这是自定义端点的内容', 'text-domain' ) . '</p>'; }
后续必要操作
- 刷新固定链接:登录WordPress后台,进入「设置」→「固定链接」,直接点击「保存更改」(无需修改设置),让WordPress更新重写规则。
- 图标替换:如果不用Font Awesome,可将代码中的
<i class="fas fa-star"></i>替换为主题自带的图标类,或者直接用文本符号代替。
关键说明
add_rewrite_endpoint是解决404的核心:必须用这个函数注册端点,否则WordPress无法识别该URL路径。- 菜单项添加:通过
woocommerce_account_menu_items过滤器将自定义端点加入账户菜单,用户才能看到访问入口。 - 文本域替换:代码中的
text-domain请替换为你的主题或插件的文本域,支持多语言翻译。
内容的提问来源于stack exchange,提问作者Behzad
相关产品推荐
相关产品推荐

