我在网上搜索了很多这个问题,但还没有找到答案。 所以我依赖这里的专家。
我想禁用一些 woocommerce 端点。网络告诉我通过
woocommerce_account_menu_items
钩子取消设置 woocommerce 菜单项,例如:
add_filter ( 'woocommerce_account_menu_items', 'my_remove_my_account_links' );
function my_remove_my_account_links( $menu_links ){
/**
* Uncomment the appropriate lines to remove specific
* endpoints in the WooCommerce My Account screen.
*/
//unset( $menu_links['dashboard'] ); // Remove Dashboard
//unset( $menu_links['edit-address'] ); // Addresses
//unset( $menu_links['payment-methods'] ); // Remove Payment Methods
//unset( $menu_links['orders'] ); // Remove Orders
//unset( $menu_links['downloads'] ); // Disable Downloads
//unset( $menu_links['edit-account'] ); // Remove Account details tab
//unset( $menu_links['customer-logout'] ); // Remove Logout link
return $menu_links;
}
但是这里的一个大问题是,这只删除了前端的菜单链接。 我仍然可以通过直接 URL 输入未设置的端点。所以当我输入
https://example.de/myaccount/[unset-endpoint]
时我仍然能够到达内容。
我找到了一种通过直接 URL 输入重定向访问的方法。我使用位于付款方式模板 (/woocommerce/templates/myaccount/ payment-methods.php) 内的钩子
woocommerce_before_account_payment_methods
重定向回仪表板:
function redirect_forbidden_access_account_endpoints(){
wp_redirect(wc_get_account_endpoint_url('dashboard'));
}
add_action('woocommerce_before_account_payment_methods', 'redirect_forbidden_access_account_endpoints');
这就像一个魅力,但仅适用于
payment-methods
端点。我对本机 downloads
端点和自定义端点尝试了此操作,但没有成功。
所以我的问题是:我有一个可靠的解决方案可以将 URL 访问从特定禁用的 woocommerce 端点重定向到仪表板吗?
您可以使用以下 2 种方式来完成:
将空值放入后端设置
转到 WooCommerce > 设置 > 高级,然后在帐户端点中
输入您可以删除特定端点的值并保存
空值。
这样,您将不会在帐户页面上看到端点页面或菜单项,如果您访问该网址,您将在访问的网址上看到主页。
取消设置查询变量
您可以使用过滤器挂钩取消设置查询变量。
https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/includes/class-wc-query.php#L85
在第
85
行中,您可以找到包含所有查询变量的函数。 在这两种情况下,您都不会看到 404 页面。
答案是:有!我的钩子错了。我现在用的是wp钩子。这合法吗?
function redirect_forbidden_access(){
$current_endpoint = WC()->query->get_current_endpoint();
if($current_endpoint == "payment-methods"
|| $current_endpoint == "add-payment-method"
|| $current_endpoint == "edit-payment-method"
|| $current_endpoint == "[custom-endpoint]")
{
wp_redirect(wc_get_account_endpoint_url('dashboard'));
}
}
add_action('wp', 'redirect_forbidden_access');
这个就可以了。
重定向和从查询变量中删除端点的组合对我有用。
如果没有重定向,端点仍会显示
wp-content/plugins/woocommerce/templates/myaccount/dashboard.php
欢迎页面中的内容。
<?php
const DISABLED_WC_ENDPOINTS = [
'bookings',
'edit-address',
'downloads',
'orders',
];
add_action(
'init',
static function () {
add_filter(
'woocommerce_get_query_vars',
static function(array $vars) {
foreach (DISABLED_WC_ENDPOINTS as $rem) {
unset($vars[$rem]);
}
return $vars;
},
0
);
}
);
add_action(
'template_redirect',
static function() {
$baseEndpoint = 'my-account';
foreach (DISABLED_WC_ENDPOINTS as $endpoint) {
if ('/' . $baseEndpoint . '/' . $endpoint . '/' === $_SERVER['REQUEST_URI']) {
wp_redirect('/' . $baseEndpoint, 301);
exit();
}
}
}
);