开发者

WordPress - Displaying Subpages (Title and Thumbnail) ON Subpages

开发者 https://www.devze.com 2023-02-27 01:19 出处:网络
I am using the following code to display a list of sub-pages and the featured post imagefrom those sub-pages in the sidebar, when on the parent page.

I am using the following code to display a list of sub-pages and the featured post image from those sub-pages in the sidebar, when on the parent page.

<?php $args = array(
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'post_parent' => $post->ID,
        'post_type' => 'page',
        'post_status' => 'publish'
        ); 
        $postslist = get_posts($args);
        foreach ($postslist as $post) : setup_postdata($post); 
    ?>
    <div class="top10">
    <a href="<?php the_permalink();?>">
    <?php the_post_thumbnail('large'); ?>
    </a>
    </div>
    <?php endforeach; ?>
    <?php wp_reset_query(); ?>

However, I also need to display the same list in the sidebar when ON one of the sub-pages. Currently, using the same code without adjustment displays nothing when on a sub-page.

I tried altering the line "'post_parent' => $post->ID开发者_如何学Go," to "'post_parent' => $post->ID."echo=0"," which displayed some of the sub-pages, but not all of them so I obviously messed something up.

Can someone help me with modifying the code to work on the sub-pages of the parent, as well as on the parent?

Thanks Zach


Use this function to generate the ID for your menu. It will determine if the page has a parent, and use that ID, otherwise it returns current page ID.

function get_menu_id(){
    if ($post->post_parent)  {
        $parent = get_post_ancestors($post->ID);
        return $parent[0];
    } else {
        return $post->ID;
    }
}

Full Code

<?php 


function get_menu_id(){ //this function would be better off in your functions.php file
        if ($post->post_parent)  {
            $parent = get_post_ancestors($post->ID);
            return $parent[0];
        } else {
            return $post->ID;
        }
    }
$args = array(
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'post_parent' => get_menu_id(),
        'post_type' => 'page',
        'post_status' => 'publish'
        ); 
        $postslist = get_posts($args);
        foreach ($postslist as $post) : setup_postdata($post); 
    ?>
    <div class="top10">
    <a href="<?php the_permalink();?>">
    <?php the_post_thumbnail('large'); ?>
    </a>
    </div>
    <?php endforeach; ?>
    <?php wp_reset_query(); ?>
0

精彩评论

暂无评论...
验证码 换一张
取 消