【问题标题】:PHP to display div only for parent postsPHP仅显示父帖子的div
【发布时间】:2026-02-01 12:45:01
【问题描述】:

我有两种类型的作品集帖子:父帖子和子帖子。当显示作为父级的单个帖子时,我希望显示:

                <div class="col-1 art-singles art-controls">
                  <?php next_post_link('%link', '←'); ?>  &nbsp;
                    <a href="<?php get_home_url(); ?>/work" alt="all work">All</a>&nbsp;  
                  <?php previous_post_link('%link', '→'); ?>
                  <a href="#" alt="enlarge image" class="enlarge-it"><p style="text-transform: none;">Enlarge</p></a>
                </div>

在子帖子中,我希望显示上述内容的细微变化。

现在,我正在使用它在所有单个帖子页面上显示菜单,无论它们是父帖子还是子帖子:

<?php if ( is_single() ) : ?>

<div class="col-1 art-singles art-controls">
   <?php next_post_link('%link', '←'); ?>  &nbsp;
   <a href="<?php get_home_url(); ?>/work" alt="all work">All</a>&nbsp;  
   <?php previous_post_link('%link', '→'); ?>
   <a href="#" alt="enlarge image" class="enlarge-it"><p style="text-transform: none;">Enlarge</p></a>
</div>

<?php endif; ?>

我不知道如何区分单亲帖子和单子帖子。

我已经尝试过以这种方式修改它以仅在父帖子上显示:

 <?php if($post->post_parent != 0) {

   echo "<?php next_post_link('%link', '←'); ?>";
   echo "&nbsp;"; 
   echo "<a href='";
   get_home_url();
   echo "/work' alt='all work'>All</a>";
   echo "&nbsp;";
   echo "<?php previous_post_link('%link', '→'); ?>";
  }
  ?>

这只是导致内容根本不显示在父或子单个帖子上。

简而言之: 我可以在 if 语句中添加一些内容以仅在父单个帖子上显示 div 吗?我可以添加一些内容以仅在子单篇文章上显示 div 吗?

【问题讨论】:

  • 这可能无法解决您的问题或与您的问题有关。但我至少看到你的代码打破了锚线。我认为您在代码中尝试执行的操作应该是 `echo 'All';

标签: php wordpress


【解决方案1】:

你也许可以在你的functions.php中使用这个is_tree()函数:

/**
 * @param  [pid] The ID of the post to check
 * @return boolean
 */
function is_tree($pid) {
    global $post;
    $cpid = get_the_ID();
    $parents = get_post_ancestors( $post->ID );
    $ancestorid = ($parents) ? $parents[count($parents)-1]: $post->ID;
    if( ($post->post_parent == $pid || $cpid == $pid || $ancestorid == $pid ))
        return true;
    return false;
};

然后像这样在你的模板中调用它:

// Use
if ( is_tree($post_id) ) {
    // do stuff
}

【讨论】: