完全禁用WooCommerce端点
P粉596191963
P粉596191963 2023-08-27 23:22:49
[PHP讨论组]

我在网上搜索了很多,但还没有找到答案。 所以我在这里依赖专家们。

我想禁用一些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端点和自定义端点进行同样的操作,但没有成功。

所以我的问题是:有没有一种可靠的解决方案,将从特定禁用的WooCommerce端点的URL访问重定向到仪表板?

P粉596191963
P粉596191963

全部回复(2)
P粉725827686

您可以通过以下两种方式来实现:

  1. 在后台设置中放置空值
    转到WooCommerce > 设置 > 高级,然后在帐户端点输入框中,您可以删除特定端点的值并保存空值。

    通过这种方式,您将不会在帐户页面上看到端点页面或菜单项,如果您访问该URL,您将在访问的URL上看到主页。

  2. 取消设置查询变量
    您可以使用过滤器钩子取消设置查询变量。 https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/includes/class-wc-query.php#L85
    在第85行,您可以找到具有所有查询变量的函数。

    https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/includes/class-wc-query.php#L232
    而在第232行,您可以找到获取查询变量的函数,它也具有过滤器。您可以使用过滤器并取消设置所需的端点。

    如果您使用此方法,您还需要从导航菜单项中取消设置该项,您还需要重新保存固定链接设置。

    然后,如果您访问该端点的URL,您将在访问的URL上看到主页。

在这两种情况下,您将不会看到404页面。

P粉217629009

答案是:是的,有!我的钩子写错了。我现在使用了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');

这就是解决方法。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号