wp_page_menu()
云策文档标注
概述
wp_page_menu() 函数用于显示或检索页面列表,并可选添加首页链接。它基于 wp_list_pages() 构建,支持多种参数来自定义输出,如排序、容器元素和 Walker 实例。
关键要点
- 函数核心功能是生成页面菜单,可输出 HTML 或返回字符串,取决于 echo 参数。
- 参数继承自 wp_list_pages(),包括 sort_column、child_of、exclude 等,用于控制页面查询和显示。
- 支持 show_home 参数添加首页链接,可自定义文本和前后 HTML。
- 使用 item_spacing 控制 HTML 中的空白保留,可选 'preserve' 或 'discard'。
- 可通过 walker 参数自定义 Walker 实例来遍历页面列表。
- 提供两个过滤器钩子:wp_page_menu_args 用于修改参数,wp_page_menu 用于修改输出 HTML。
- 默认容器为 div,但可通过 container 参数更改,如设置为 ul 以兼容 wp_nav_menu 样式。
- 函数内部处理了首页链接的添加和排除逻辑,确保与站点设置一致。
代码示例
// 示例1:添加“Home”链接,排除特定页面,按菜单顺序排序
wp_page_menu( array(
'show_home' => true,
'exclude' => '5,9,23',
'sort_column' => 'menu_order',
'before' => '<h2>Page Menu</h2>'
) );
// 示例2:自定义首页链接文本为“Blog”
wp_page_menu( array( 'show_home' => 'Blog', 'sort_column' => 'menu_order' ) );
// 示例3:仅显示首页链接,通过 include 参数限制
wp_page_menu( array( 'show_home' => true, 'include' => 9999 ) );注意事项
- show_home 参数可能被主题覆盖,导致设置无效,建议直接使用 wp_list_pages() 自定义包装器以获得更稳定控制。
- 使用 container 参数时,注意与 wp_nav_menu 的样式兼容性,例如设置为 ul 以匹配默认菜单结构。
- 参数 item_spacing 仅接受 'preserve' 或 'discard',无效值会回退到默认 'discard'。
- 函数依赖于 wp_list_pages(),因此相关参数(如 hierarchical、meta_key)的行为需参考该函数文档。
原文内容
Displays or retrieves a list of pages with an optional home link.
Description
The arguments are listed below and part of the arguments are for wp_list_pages() function.
Check that function for more info on those arguments.
Parameters
$argsarray|stringoptional-
Array or string of arguments to generate a page menu. See wp_list_pages() for additional arguments.
sort_columnstringHow to sort the list of pages. Accepts post column names.
Default ‘menu_order, post_title’.menu_idstringID for the div containing the page list. Default is empty string.menu_classstringClass to use for the element containing the page list. Default'menu'.containerstringElement to use for the element containing the page list. Default'div'.echoboolWhether to echo the list or return it. Accepts true (echo) or false (return).
Default true.show_homeint|bool|stringWhether to display the link to the home page. Can just enter the text you’d like shown for the home link.1|truedefaults to'Home'.link_beforestringThe HTML or text to prepend to $show_home text.link_afterstringThe HTML or text to append to $show_home text.beforestringThe HTML or text to prepend to the menu. Default is<code><ul>.afterstringThe HTML or text to append to the menu. Default is<code></ul>.item_spacingstringWhether to preserve whitespace within the menu’s HTML. Accepts'preserve'or'discard'. Default'discard'.walkerWalkerWalker instance to use for listing pages. Default empty which results in a Walker_Page instance being used.
More Arguments from wp_list_pages( … $args )
Array or string of arguments to retrieve pages.
child_ofintPage ID to return child and grandchild pages of. Note: The value of$hierarchicalhas no bearing on whether$child_ofreturns hierarchical results. Default 0, or no restriction.sort_orderstringHow to sort retrieved pages. Accepts'ASC','DESC'. Default'ASC'.sort_columnstringWhat columns to sort pages by, comma-separated. Accepts'post_author','post_date','post_title','post_name','post_modified','menu_order','post_modified_gmt','post_parent','ID','rand','comment*count'.
'post*'can be omitted for any values that start with it.
Default'post_title'.hierarchicalboolWhether to return pages hierarchically. If false in conjunction with$child_ofalso being false, both arguments will be disregarded.
Default true.excludeint[]Array of page IDs to exclude.includeint[]Array of page IDs to include. Cannot be used with$child_of,$parent,$exclude,$meta_key,$meta_value, or$hierarchical.meta_keystringOnly include pages with this meta key.meta_valuestringOnly include pages with this meta value. Requires$meta_key.authorsstringA comma-separated list of author IDs.parentintPage ID to return direct children of. Default -1, or no restriction.exclude_treestring|int[]Comma-separated string or array of page IDs to exclude.numberintThe number of pages to return. Default 0, or all pages.offsetintThe number of pages to skip before returning. Requires$number.
Default 0.post_typestringThe post type to query. Default'page'.post_statusstring|arrayA comma-separated list or array of post statuses to include.
Default'publish'.
Default:
array()
Source
function wp_page_menu( $args = array() ) {
$defaults = array(
'sort_column' => 'menu_order, post_title',
'menu_id' => '',
'menu_class' => 'menu',
'container' => 'div',
'echo' => true,
'link_before' => '',
'link_after' => '',
'before' => '<ul>',
'after' => '</ul>',
'item_spacing' => 'discard',
'walker' => '',
);
$args = wp_parse_args( $args, $defaults );
if ( ! in_array( $args['item_spacing'], array( 'preserve', 'discard' ), true ) ) {
// Invalid value, fall back to default.
$args['item_spacing'] = $defaults['item_spacing'];
}
if ( 'preserve' === $args['item_spacing'] ) {
$t = "t";
$n = "n";
} else {
$t = '';
$n = '';
}
/**
* Filters the arguments used to generate a page-based menu.
*
* @since 2.7.0
*
* @see wp_page_menu()
*
* @param array $args An array of page menu arguments. See wp_page_menu()
* for information on accepted arguments.
*/
$args = apply_filters( 'wp_page_menu_args', $args );
$menu = '';
$list_args = $args;
// Show Home in the menu.
if ( ! empty( $args['show_home'] ) ) {
if ( true === $args['show_home'] || '1' === $args['show_home'] || 1 === $args['show_home'] ) {
$text = __( 'Home' );
} else {
$text = $args['show_home'];
}
$class = '';
if ( is_front_page() && ! is_paged() ) {
$class = 'class="current_page_item"';
}
$menu .= '<li ' . $class . '><a href="' . esc_url( home_url( '/' ) ) . '">' . $args['link_before'] . $text . $args['link_after'] . '</a></li>';
// If the front page is a page, add it to the exclude list.
if ( 'page' === get_option( 'show_on_front' ) ) {
if ( ! empty( $list_args['exclude'] ) ) {
$list_args['exclude'] .= ',';
} else {
$list_args['exclude'] = '';
}
$list_args['exclude'] .= get_option( 'page_on_front' );
}
}
$list_args['echo'] = false;
$list_args['title_li'] = '';
$menu .= wp_list_pages( $list_args );
$container = sanitize_text_field( $args['container'] );
// Fallback in case `wp_nav_menu()` was called without a container.
if ( empty( $container ) ) {
$container = 'div';
}
if ( $menu ) {
// wp_nav_menu() doesn't set before and after.
if ( isset( $args['fallback_cb'] ) &&
'wp_page_menu' === $args['fallback_cb'] &&
'ul' !== $container ) {
$args['before'] = "<ul>{$n}";
$args['after'] = '</ul>';
}
$menu = $args['before'] . $menu . $args['after'];
}
$attrs = '';
if ( ! empty( $args['menu_id'] ) ) {
$attrs .= ' id="' . esc_attr( $args['menu_id'] ) . '"';
}
if ( ! empty( $args['menu_class'] ) ) {
$attrs .= ' class="' . esc_attr( $args['menu_class'] ) . '"';
}
$menu = "<{$container}{$attrs}>" . $menu . "<!--{$container}-->{$n}";
/**
* Filters the HTML output of a page-based menu.
*
* @since 2.7.0
*
* @see wp_page_menu()
*
* @param string $menu The HTML output.
* @param array $args An array of arguments. See wp_page_menu()
* for information on accepted arguments.
*/
$menu = apply_filters( 'wp_page_menu', $menu, $args );
if ( $args['echo'] ) {
echo $menu;
} else {
return $menu;
}
}
Hooks
- apply_filters( ‘wp_page_menu’, string $menu, array $args )
-
Filters the HTML output of a page-based menu.
- apply_filters( ‘wp_page_menu_args’, array $args )
-
Filters the arguments used to generate a page-based menu.
Skip to note 5 content
Codex
Display Home as a Page
The following example causes “Home” to be added to the beginning of the list of pages displayed. In addition, the Pages wrapped in a
divelement, page IDs 5, 9, and 23, are excluded from the list of pages displayed, and the pages are listed in Page Order. The list is prefaced with the title “Page Menu”.<h2>Page Menu</h2>Skip to note 6 content
Codex
Display Home as a Page called Blog
The following example causes “Blog” (instead of “Home”) to be added to the beginning of the list of pages displayed:
'Blog', 'sort_column' => 'menu_order' ) ); ?>Skip to note 7 content
Codex
Display only Home
The following example displays just a link to “Home”. Note that the include=9999′ references a page ID that does not exist so only a link for Home is displayed.
Skip to note 8 content
gabbsmo
$args['show_home'] = falsewill not always work as it is often overriden by themes, including default themes. It will also set the class on the wrapping block element, not the root level unorded list, like wp_nav_menu. If you want your styles for wp_nav_menu to work, I recommend that you usewp_list_pageswith your own wrapper.