如何为WooCommerce我的账户自定义菜单项设置自定义链接?
解决WooCommerce账户菜单自定义外部链接问题
你的代码问题在于:直接将外部URL作为菜单项目的键时,WooCommerce会默认把这个键当作账户页面的endpoint,自动拼接到my-account URL路径后,导致生成错误的链接;同时str_replace直接处理数组$items是无效操作。
按照以下步骤修改代码,即可实现自定义外部链接:
1. 添加自定义菜单项目到账户菜单
先给菜单项目设置一个自定义的endpoint名称(而非直接用URL):
function custom_add_my_account_menu_item($items) { // 使用自定义标识作为键,而非外部URL $items['custom_external_link'] = __('NEW CUSTOM TAB', 'your-text-domain'); return $items; } add_filter('woocommerce_account_menu_items', 'custom_add_my_account_menu_item');
2. 拦截endpoint,返回外部链接
通过woocommerce_get_endpoint_url过滤器,将我们自定义的endpoint替换为目标外部URL:
function custom_modify_external_endpoint_url($url, $endpoint, $value, $permalink) { // 匹配自定义的endpoint标识 if ($endpoint === 'custom_external_link') { // 返回你需要的外部链接地址 return 'https://mycustomwebsite.com/'; } return $url; } add_filter('woocommerce_get_endpoint_url', 'custom_modify_external_endpoint_url', 10, 4);
额外说明
- 因为菜单点击后会直接跳转到外部网站,原代码中用于显示账户页面内容的
custom_my_account_endpoint_content函数及对应的action可以删除,无需保留。 - 确保替换代码中的
your-text-domain为你主题的文本域,或者直接去掉第二个参数(如果不需要翻译)。
内容的提问来源于stack exchange,提问作者Luis Cabré
相关产品推荐
相关产品推荐

