【问题标题】:Get only the grandchildren, not the direct children of page/current page?只获取孙子,而不是页面/当前页面的直接子项?
【发布时间】:2016-02-25 14:44:56
【问题描述】:

我现在非常了解 javascript,但我对 php 和 wordpress 主题构建还很陌生。我进行了相当多的搜索,但找不到解决看似非常简单的任务的解决方案,我想要完成的只是获取页面的所有孙子,而不是直接子孙,如下所示:

投资组合

  • 孩子 1
    • 孙子1A
    • 孙子 1B
  • 孩子 2
    • 孙子2A
    • 孙子2B

我的页面是“Portfolio”,我想“get_pages”,但只返回“Portfolio”的孙子页面,所以在这种情况下,它只会返回:-“grandchild 1A”、“grandchild 1B”、“grandchild” 2A”、“孙子 2B”。

<?php
$portfolio = get_pages( array( 
   'child_of' => $post->ID));

       foreach( $portfolio as $page ) { 
       //My idea here was to check if the page that is being looped through, was a direct child of portfolio, if so then it would skip it.
         if($page !== 'child_of' => $post) {    
         echo $page->post_title; 
              }
       }?>

有什么建议吗?

编辑:

<?php
$grandchildren = get_pages( array( 'child_of' => $portfolioPageId ) );
foreach( $grandchildren as $grandchild ) {
if($grandchild->post_parent != $portfolioPageId ){   

    echo $grandchild->post_title; 

}}?>

【问题讨论】:

  • 到目前为止你尝试过什么?请阅读How to Ask 了解有关编写高质量问题的一些提示。
  • 好的,我更新了我目前的问题。

标签: php wordpress foreach wordpress-theming


【解决方案1】:

查看此代码,该代码使用child_of 参数获取投资组合页面ID,并排除post_parent 等于您的投资组合页面ID 的页面。

<?php
$grandchildren = get_pages( array( 'child_of' => $portfolioPageId ) );
foreach( $grandchildren as $grandchild ) {
    if($grandchild->post_parent != $portfolioPageId ){   
        // Whatever you need
    }
}

【讨论】:

  • 这只是获取子页面......这是他不想要的 - 他想要您的代码将列出的页面的子页面。您可以使用您的代码来存储子页面 id - 然后使用引用 id 作为 child_of 参数的相同代码循环遍历它们,但我不确定解决方案有多优雅:)
  • 看看here,上面说只列出单个Page的子页面;使用 Page 的 ID 作为值。默认为 0(列出所有页面)。 请注意,child_of 参数还将获取给定 ID 的“孙子”,而不仅仅是直接后代。
  • 是的,它也获取了子页面 - 这就是问题所在 - 解决方案需要一种排除它们的方法
  • $grandchild-&gt;post_parent != $portfolioPageId不是解决问题了吗?如果你得到所有的孩子和孙子,并排除 post_parent 等于 $portfolioPageId 的页面,你应该只有孙子
  • 我想对该评论投赞成票 :p 很高兴不仅仅是我,我希望 @William-Larsen-Bang 现在能看到你的答案 :)
【解决方案2】:

如果你使用的是 JS,那么你可以使用querySelectorAll。这会给你所有的大子节点。你可以这样使用它:

var getNodes = document.querySelectorAll("grandparent > parent grandchild");

【讨论】:

  • 你好,moomdid。感谢您对 SO 的贡献。请考虑在回答时使用格式化工具。它们使您的答案看起来更具可读性。您现在可以通过单击编辑按钮重新格式化您的答案。
猜你喜欢
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多