phpwordpresswoocommercewordpress-themingwordpress-plugin-creation

Fully disable WooCommerce Endpoints


I've searched the web a lot for this but i did not found an answer yet. So i rely on the specialists here.

I want to disable some woocommerce endpoints. The web told me to unset the woocommerce menu items via woocommerce_account_menu_items hook like:

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;
}

BUT the big problem here is that this only removes the menu links in the frontend. I can still enter the unset endpoints via direct URL. So when i enter https://example.de/myaccount/[unset-endpoint] i am still abled to reach the content.

I found one way to redirect access via direct URL entry. I used the hook woocommerce_before_account_payment_methods which is located inside the payment methods template (/woocommerce/templates/myaccount/payment-methods.php) to redirect back to the dashboard:

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');

This works like a charme BUT only for the payment-methods endpoint. I tried this for the native downloads endpoint and a custom endpoint aswell without success.

So my question is: I there a solid solution to redirect URL access from specific disabled woocommerce endpoints to the dashboard?


Solution

  • Answer is: Yes there is! My hook was wrong. I used the wp hook now. Is that legal?

    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');
    

    This does the trick.