How can i add a custom endpoint as a my account page menu item?

To do this, first, we need to add an endpoint using the WordPress function called add_rewrite_endpoint() using the ‘init’ action hook like:

function wpartisan_custom_endpoint() {
	add_rewrite_endpoint( 'custom-menu', EP_PAGES  );
	if( !get_option('rw_permalinks_flushed') ) {
        flush_rewrite_rules(false);
        update_option('rw_permalinks_flushed', 1);
 
    }
}

add_action( 'init', 'wpartisan_custom_endpoint' );

In the function add_rewrite_endpoint(), the first parameter is the endpoint’s name, and the second parameter means where the endpoint will add as query arguments. For example, EP_PAGES means it will add a new rewrite rule ending with “custom-menu(/(.*))?/?$” for every page. So when you will visit your page URL like https://{your domain name}/my-account/custom-menu/foo/, then you will see your global $wp_query object like the below image:

My account custom menu

I use the flush_rewrite_rules() function inside the custom endpoint creation function because if you do not flush, then when you try to access this custom menu, it will go to a 404 page. You can do this manually also from Settings-> Permalinks in the admin area.

For more understanding, visit https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint.

Add a Menu Item

Now, we need to add a menu item for this custom endpoint on WooCommerce My Account page menu. To achieve this feature, we need to use the ‘woocommerce_account_menu_items’ filter like the below:

add_filter( 'woocommerce_account_menu_items', 'wpartisan_new_menu_items' );
function wpartisan_new_menu_items( $items ) {
	$items[ 'custom-menu' ] = __( 'Custom Menu', 'wpartisan' );
	return $items;
}

Add Content for the Menu Item

Now the final step is to show content for this custom endpoint, which means when you visit that URL, which content will be shown for that? For that, WooCommerce provides a hook, and we can use this like below:

$endpoint = 'custom-menu';

add_action( 'woocommerce_account_' . $endpoint .  '_endpoint', 'wpartisan_endpoint_content' );

function wpartisan_endpoint_content() {
	//echo $args_val = get_query_var( 'custom-menu', 1 );
    //Custom menu content goes here
    echo 'Custom menu content goes here';    
}
My account custom menu

Menu item order change

In addition, if you want to modify the navigation menu order of the My Account page for the newly created menu item, you need to add the code like the one below:

add_filter( 'woocommerce_account_menu_items', 'wpartisan_new_menu_items' );
function wpartisan_new_menu_items( $items ) {
	
	$items = array_slice( $items, 0, 3, true )
	+ array( 'custom-menu' => __( 'Custom Menu', 'wpartisan' ) )
	+ array_slice( $items, 3, count( $items ), true );

	return $items;
}

Then the final output will be like this:

My account custom menu item order change

Leave a Reply

Your email address will not be published. Required fields are marked *