Show Child Posts of Parent Function Wordpress

Viewed 26

I have created a template on wordpress where I want to output the child posts of certain parent posts. It will output 5 child posts to the corresponding parent post.

Parent post

  • Child Post
  • Child Post
  • Child Post

The code for this, looks like this:

  function vd_list_child_pages( $atts = array() ) {
    $atts = shortcode_atts( array(
        'id'   => 0,
        'slug' => '',
    ), $atts );

    $post_id = absint( $atts['id'] );
    $post = get_post( $post_id ); // WP_Post on success.
    $childpages = '';

          if ( $post && is_post_type_hierarchical( 'page' ) ) {
        $childpages = wp_list_pages( array(
            'child_of' => $post->ID,
            'title_li' => '',
            'echo'     => 0,
            'depth'        => 1,
            'link_before'  => '<i class="far fa-file-alt"></i>',
            'walker'       => '',
        ) );
    }

    if ( $childpages ) {
        $childpages = '<ul class="child-posts-content">' . $childpages . '</ul>';
        
    }
    return $childpages;
      

}
add_shortcode( 'vd_childpages', 'vd_list_child_pages' ); 

However, I need the code in the template more often, with different "post_parent" ID's. Do I have to use the code everywhere like this, or can I create a "function", or which option is correct here?

0 Answers
Related