检查WordPress中的post_parent = 0

时间:2015-02-17 13:06:28

标签: php wordpress

我正在使用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 id0是否在WordPress中是不允许的,并将帖子id设置为post_parent但是我'我不是100%肯定。

2 个答案:

答案 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)

据我所知,此代码片段执行以下操作:

  1. 加载全局帖子对象。
  2. 加载全局查询对象。
  3. 检查(或尝试检查)当前帖子是否有父过滤器(?)。
  4. 如果有,则将变量$ thePostID设置为当前帖子对象的post_parent参数的id。
  5. 如果没有,则将wp_query中的帖子ID设置为当前帖子的id。
  6. 总而言之,这似乎是非常不必要的,糟糕的表现和奇怪的Oo。 实际上有效吗? ^^

    如果可能的话,我建议你使用另一个主题; - )