简体   繁体   中英

function not returning value in “functions.php”

I have created a function within my themes functions.php file in order to persist a list of child pages from the level of a parent page while navigating deeper within the hierarchy.
My issue is that when I call the function within the page.php theme file I dont get anything back.

functions.php:

function get_top_parent_children($the_id,$start = 0,$walk = null){

    $current_post = get_post($the_id);
    $walk[] = $current_post;

    if($current_post->post_parent){
        get_top_parent_children($current_post->post_parent,$start,$walk);
    } else {
        $output = array_reverse($walk);
        return get_children($output[$start]->ID);
    }
}

page.php:

<?php get_header(); ?>
<div id="primary" class="clearfix">

    <div id="content">
        <?php the_post(); ?>
        <?php $children = get_top_parent_children($id,1); ?>
        <?php if ( $children ) { ?>
            <section id="post-topic">
                <h2><?php the_title() ?> Topics</h2>
                <ul class="clearfix">
                    <?php foreach( $children as $child){ ?>
                        <li>
                            <a href="<?php echo get_permalink($child->ID) ?>"> <?php echo child->post_title ?> </a>
                        </li>
                    <?php }; ?>
                </ul>
            </section>
        <?php }; ?>
        <?php get_template_part( 'content', 'page' ); ?>
    </div>
    <aside>
        <?php dynamic_sidebar('Page Sidebar'); ?> 
    </aside>
</div>
<?php get_footer(); ?>

I guess you forgot the second return . You have an if with two code paths, but only return a value in the last one. You need:

if($current_post->post_parent){
    return get_top_parent_children(...);
   # ^^^^
} else {
    return get_children(...);
}

Your function is (recursively) calling itself when that condition matches. But you still need to instruct PHP that it should pass on the value to the outer call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM