我正在使用WordPress创建一个网站,该主题在每个页面的顶部都有这个PHP,我对它的作用感到困惑.
<?php
global $post;
global $wp_query;
if ( $post->post_parent != 0 ) {
$thePostID = $post->post_parent;
} else {
$thePostID = $wp_query->post->ID;
};
?>
Run Code Online (Sandbox Code Playgroud)
我只是想知道是否有人能够确切地解释这是做什么的?我认为它会检查,看看是否post_parent id就是0未在WordPress的允许和设置后id到post_parent,但我不是100%肯定.
我认为它会检查post_parent id是否为0,而WordPress中是不允许的
所述$post->post_parent允许是0.如果该值为0,它只是意味着该页是一个顶层页.
页面具有$post->post_parent0以外的页面,是另一页面的子页面.
例如,以此页面结构为例:
id page_title post_parent
1 Home 0
2 About 0
3 Staff 2
4 History 2
5 Contact 0
Run Code Online (Sandbox Code Playgroud)
生成的页面/菜单结构将是:
有问题的代码:
if ($post->post_parent != 0){
$thePostID = $post->post_parent;
} else {
$thePostID = $wp_query->post->ID;
}
Run Code Online (Sandbox Code Playgroud)
我不确定您的主题可能具有代码的具体原因,但可能的原因可能是获取与当前页面相关的菜单.如果您正在查看顶级页面(即$post->post_parent= 0),那么它将显示所有子页面,或者如果您正在查看子页面,则菜单可能会显示所有同级页面.
将其添加到您的functions.php文件中,以便在整个主题中可以访问它.
/**
* Get top parent for the current page
*
* If the page is the highest level page, it will return it's own ID, or
* if the page has parent(s) it will get the highest level page ID.
*
* @return integer
*/
function get_top_parent_page_id() {
global $post;
$ancestors = $post->ancestors;
// Check if page is a child page (any level)
if ($ancestors) {
// Grab the ID of top-level page from the tree
return end($ancestors);
} else {
// Page is the top level, so use it's own id
return $post->ID;
}
}
Run Code Online (Sandbox Code Playgroud)
将此代码添加到要显示菜单的主题中.您需要自定义此选项以满足您的特定需求,但它会为您提供一个示例,说明为什么有人可能会使用您询问的代码.
// Get the highest level page ID
$top_page_id = get_top_parent_page_id();
// Display basic menu for child or sibling pages
$args = array(
'depth' => 1,
'title_li' => FALSE,
'sort_column' => 'menu_order, post_title',
'child_of' => $top_page_id
);
echo wp_list_pages($args);
Run Code Online (Sandbox Code Playgroud)