The use of add_action()
seems backwards to me. A better approach would be to hook homepage_content()
into the homepage
hook and then just output each section within the one hook:
function homepage_content() {
$the_id = 5;
$item = get_post( $the_id );
$page_tree_array = get_pages( array(
'child_of' => $the_id
) );
foreach( $page_tree_array as $item ) {
$id = $item->ID;
$slug = $item->post_name;
$title = apply_filters( 'the_title', $item->post_title );
$content = apply_filters( 'the_content', $item->post_content );
?>
<article id="post-<?php echo $id; ?>" <?php post_class( 'homepage-content' ); ?>>
<h1><?php echo $title; ?></h1>
<?php echo $content; ?>
</article>
<?php
}
}
add_action( 'homepage', 'homepage_content' );
There’s some other changes you could make that would help too, but I left out to focus on the use of add_action()
:
- Get the homepage ID dynamically with
get_option( 'page_on_front' )
. - Setting
$item
to theget_post()
value for the ID seems unnecessary, since you never use it. - Use
setup_postdata()
for each section so that you can use template tags likethe_title()
andthe_content()
. - Using
setup_postdata()
also means you could put the homepage section template into a separate file and call it withget_template_part()
.
Taking all that into account and your homepage_content()
function would look like this:
function homepage_content() {
global $post;
$child_pages = get_pages( array(
'child_of' => get_option( 'page_on_front' ),
) );
foreach ( $child_pages as $post ) {
setup_postdata( $post );
get_template_part( 'partials/homepage-content' );
}
wp_reset_postdata();
}
add_action( 'homepage', 'homepage_content' );
Then create partials/homepage-content.php
as the template for each section. Since setup_postdata()
was used you can use the proper template tags:
<article id="post-<?php the_ID(); ?>" <?php post_class( 'homepage-content' ); ?>>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
</article>