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

My account custom menu To do this, first we need to add rewrite endpoint using WordPress function ‘add_rewrite_endpoint’ on ‘init’ 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 function add_rewrite_endpoint() , first parameter is the name of the endpoint. Second parameter means where the endpoint will add as query arguments. For example, EP_PAGES means will add a new rewrite rule ending with “custom-menu(/(.*))?/?$” for every pages. So when you will visit you pages URL like <premalink>/custom-menu/foo/ then you will see your global $wp_query object like below image:

My account custom menu

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

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

Now, we need to add menu item for this custom endpoint on WooCommerce My Account page menu. To achieve this feature we need to use ‘woocommerce_account_menu_items’ filter like 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;
}

Now final step is need to show content for this custom endpoint, means when you visit that URL, which content will be show for that? For that WooCommerce provide 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';    
}

Leave a Reply

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