以下代码将 WooCommerce 我的帐户页面的子页面添加到我的帐户页面的菜单中。我希望子页面的内容显示在我的帐户页面的内容部分中,但是,当前添加的页面显示仪表板内容而不是页面的内容。我不确定问题出在哪里。
这是我的相关代码:
// Register rewrite endpoints for all child pages
function register_dynamic_my_account_endpoints() {
$my_account_page_id = get_option('woocommerce_myaccount_page_id');
if ($my_account_page_id) {
$child_pages = get_pages(['child_of' => $my_account_page_id]);
foreach ($child_pages as $page) {
add_rewrite_endpoint($page->post_name, EP_ROOT | EP_PAGES);
}
}
}
add_action('init', 'register_dynamic_my_account_endpoints');
// Flush rewrite rules on activation
function flush_rewrite_rules_after_update() {
register_dynamic_my_account_endpoints();
flush_rewrite_rules();
}
add_action('admin_init', 'flush_rewrite_rules_after_update');
// Display the content of dynamic My Account pages
function display_dynamic_my_account_content() {
$current_endpoint = WC()->query->get_current_endpoint();
if (!$current_endpoint) {
return;
}
$page = get_page_by_path($current_endpoint);
if ($page) {
echo '<h3>' . esc_html($page->post_title) . '</h3>';
echo apply_filters('the_content', $page->post_content);
}
}
add_action('woocommerce_account_content', 'display_dynamic_my_account_content');
// Dynamically add child pages of My Account to the menu above Logout
function add_dynamic_my_account_pages($items) {
$my_account_page_id = get_option('woocommerce_myaccount_page_id');
if (!$my_account_page_id) {
return $items;
}
$child_pages = get_pages(['child_of' => $my_account_page_id, 'sort_column' => 'menu_order']);
$dynamic_pages = [];
foreach ($child_pages as $page) {
$slug = $page->post_name;
$dynamic_pages[$slug] = $page->post_title;
}
if (isset($items['customer-logout'])) {
$logout_item = ['customer-logout' => $items['customer-logout']];
unset($items['customer-logout']);
$items = array_merge($items, $dynamic_pages, $logout_item);
} else {
$items = array_merge($items, $dynamic_pages);
}
return $items;
}
add_filter('woocommerce_account_menu_items', 'add_dynamic_my_account_pages');
有时,操作的优先级可能会发生冲突,并且内容可能无法按预期显示。您可以尝试调整操作挂钩的优先级,以确保在 WooCommerce 呈现其默认内容后显示您的自定义内容。 之后添加延迟
function display_dynamic_my_account_content(){ .....}
add_action('woocommerce_account_content', 'display_dynamic_my_account_content', 20);
给予较低优先级