简体   繁体   中英

Can I display a custom template page linked to a child page on a parent page - Wordpress

I'm creating a Wordpress template from scratch for my company's website. I don't know much about PHP but I know my old company has succeded in doing the operation I want to do but I don't find any solution on the Internet...

I would like to display in a parent page, several child page and the template page that they are linked to. That way, I could display the template page as a block that can be re-used in several other pages.

For example I created a template named home.php that will be the parent page, and a custom template introduction.php with one of my block structure. In wordpress I have created a parent page for my homepage, and a child page with my template introduction.php linked. I would like to display in my parent page, the child page and the template content to have the structure + the content of the child page.

In each parent page, I'll have several child that can have the same custom template.

I find this solution better than creating a full static page and giving it the ID of the pages or putting my HTML directly in a page editor, but I don't know if this solution exists.

For now I have only find solutions to loop child page into the custom template and then display the template with "get_template_part" into the home.php, but it displays all my templates even if they aren't link with a child page and shows the content twice...

Thank you if you can help me with this problem and sorry for my broken English.

So you want a 'parent page' that displays all the 'child page contents' in the 'parent page' itself like blocks

add this in your parent template file,

`<parent page content here>

<?php
$args = array(
    'post_parent' => $post->ID,
    'post_type' => 'page',
    'orderby' => 'menu_order',
    'order' => 'DESC'
);

$query = new WP_Query($args);

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();

    $template = get_post_meta( $post->ID, '_wp_page_template', true );

    $template = pathinfo($template);
    $template_parts = explode('-', $template['filename']);

    get_template_part( $template_parts[0], $template_parts[1] );

    endwhile;
endif;
?>`

This should get the child pages to the parent page, here i will be using the template file like this 'template-introduction.php' and i will be adding the 'introduction' as the template name. This is assuming you have different templates for the child pages.

I have't tested this, in theory this should get you what you need.

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