我正在使用WordPress创建一个网站,该主题在每个页面的顶部都有这个PHP,我对它的作用感到困惑。
<?php
global $post;
global $wp_query;
if ( $post->post_parent != 0 ) {
$thePostID = $post->post_parent;
} else {
$thePostID = $wp_query->post->ID;
};
?>
我只是想知道是否有人能够准确解释这是做什么的?我认为它会检查post_parent
id
是0
是否在WordPress中是不允许的,并将帖子id
设置为post_parent
但是我'我不是100%肯定。
答案 0 :(得分:7)
我认为它会检查post_parent id是否为0,而WordPress中是不允许的
允许$post->post_parent
为0.如果值为0,则只表示该页面是顶级页面。
页面的$post->post_parent
不是0,是另一页的子项。
例如,以此页面结构为例:
id page_title post_parent
1 Home 0
2 About 0
3 Staff 2
4 History 2
5 Contact 0
生成的页面/菜单结构将是:
有问题的代码:
if ($post->post_parent != 0){
$thePostID = $post->post_parent;
} else {
$thePostID = $wp_query->post->ID;
}
我不确定您的主题可能包含代码的具体原因,但可能的原因可能是获取与当前页面相关的菜单。如果您正在查看顶级页面(即$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;
}
}
将此代码添加到您要显示菜单的主题中。您需要对其进行自定义以满足您的特定需求,但它会为您提供一个示例,说明为什么有人可能会使用您询问的代码。
// 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);
答案 1 :(得分:0)
据我所知,此代码片段执行以下操作:
如果可能的话,我建议你使用另一个主题; - )