Skip to content

Instantly share code, notes, and snippets.

@mklasen
Created August 16, 2022 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mklasen/89e2ada0a4477653b81ffa8056e64674 to your computer and use it in GitHub Desktop.
Save mklasen/89e2ada0a4477653b81ffa8056e64674 to your computer and use it in GitHub Desktop.
Manage menu items and custom pages in Woocommerce my account dashboard
<?php
class MK_Woocommerce {
public function __construct() {
$this->init();
}
public function init() {
add_filter( 'woocommerce_account_menu_items', array( $this, 'manage_menu_items' ), 80 );
add_action( 'init', array( $this, 'add_resources_item' ) );
add_action( 'woocommerce_account_resources_endpoint', array( $this, 'resources_output' ) );
add_filter( 'woocommerce_get_query_vars', array( $this, 'add_resources_query_var' ) );
add_action( 'template_redirect', array( $this, 'set_my_account_homepage' ) ); }
/**
*
* Add Resources item to the menu items
*
* @param array $items Array of registered menu items
* @return array Array of registered and new menu items
*/
public function manage_menu_items( $items ) {
// Remove the dashboard item
unset( $items['dashboard'] );
// Add resources item before last item
$items = array_merge(
array_slice( $items, 0, count( $items ) - 1 ),
array( 'resources' => __( 'Resources', 'textdomain' ) ),
array_slice( $items, count( $items ) - 1 ),
);
return $items;
}
/**
* Register the new endpoint
*
* @return void
*/
public function add_resources_item() {
add_rewrite_endpoint( 'resources', EP_PAGES );
}
/**
* The resources endpoint output
*
* @return void
*/
public function resources_output() {
echo '<p>My custom endpoint output.</p>';
}
/**
* Register the resources query var
*
* @param array $vars Array of registered query vars.
* @return array Array of registered and new query vars.
*/
public function add_resources_query_var( $vars ) {
$vars['resources'] = 'resources';
return $vars;
}
/**
* Set the homepage for the Woocommerce my account page
*/
public function set_my_account_homepage() {
if ( is_account_page() && empty( WC()->query->get_current_endpoint() ) ) {
wp_safe_redirect( wc_get_account_endpoint_url( 'resources' ) );
exit;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment