I am working on a project where my account page is a homepage. So what I did I have created a page that holding the shortcode [woocommerce_my_account]
and made this page homepage from Dashboard->Settings->Reading. Everything works. I have this working endpoints too:
But I am facing trouble when I am making a custom myaccount endpoint. I am doing it in this traditional way:
add_action('woocommerce_account_custom-endpoint_endpoint', function(){
echo 'hello';
} );
add_action('init', function() {
add_rewrite_endpoint('custom-endpoint', EP_ROOT | EP_PAGES);
});
But mydomain.com/custom-endpoint is not pointing to my account page, it is pointing to the index.php or page.php (WordPress template hierarchy).
I am curious to know why it is happening?
Updated:
Important: You need first to declare your home page as the My account page in:
WooCommerce settings > Advanced > My account page field.
Use the following:
// Enable endpoint
add_filter( 'woocommerce_get_query_vars', 'myaccount_custom_endpoint_query_var' );
function myaccount_custom_endpoint_query_var( $query_vars ) {
$query_vars['custom-endpoint'] = 'custom-endpoint';
return $query_vars;
}
// Endpoint displayed content
add_action('woocommerce_account_custom-endpoint_endpoint', 'display_custom_endpoint_content' );
function display_custom_endpoint_content(){
echo '<p>' . __("hello") . '</p>';
}
Optionally you can use the following too:
// Add it as my account menu item
add_filter ( 'woocommerce_account_menu_items', 'custom_account_menu_items', 10 );
function custom_account_menu_items( $menu_links ){
$menu_links = array_slice( $menu_links, 0,3 , true )
+ array( 'custom-endpoint' => __('Custom Endpoint') )
+ array_slice( $menu_links, 3, NULL, true );
return $menu_links;
}
// Endpoint page title
add_filter( 'woocommerce_endpoint_custom-endpoint_title', 'set_my_account_custom_endpoint_title', 10, 2 );
function set_my_account_custom_endpoint_title( $title, $endpoint ) {
$title = __( "Custom Endpoint", "woocommerce" );
return $title;
}
Code goes in functions.php file of the active child theme (or active theme).
Edit: The hook woocommerce_get_query_vars
is mandatory and replace the function that handle add_rewrite_endpoint()
, which is not needed anymore (thanks to @Jitu).
You can flush rewrites rules if needed by going to Wordpress settings > Permalinks and "Save changes".
Tested and works.