【问题标题】:Can I display a custom template page linked to a child page on a parent page - Wordpress我可以在父页面上显示链接到子页面的自定义模板页面吗 - Wordpress
【发布时间】:2018-08-08 09:23:04
【问题描述】:

我正在为我公司的网站从头开始创建一个 Wordpress 模板。 我对PHP不太了解,但我知道我的老公司已经成功完成了我想做的操作,但是我在互联网上没有找到任何解决方案...

我想在一个父页面、几个子页面和它们链接的模板页面中显示。这样,我可以将模板页面显示为可以在其他几个页面中重复使用的块。

例如,我创建了一个名为 home.php 的模板,它将作为父页面,以及一个自定义模板 Introduction.php,其中一个是我的块结构。在 wordpress 中,我为我的主页创建了一个父页面,以及一个带有我的模板 Introduction.php 链接的子页面。 我想在我的父页面、子页面和模板内容中显示有结构+子页面的内容。

在每个父页面中,我将有几个可以具有相同自定义模板的子页面。

我发现此解决方案比创建一个完整的静态页面并为其提供页面 ID 或将我的 HTML 直接放入页面编辑器要好,但我不知道此解决方案是否存在。

目前我只能找到将子页面循环到自定义模板中的解决方案,然后在 home.php 中显示带有“get_template_part”的模板,但它会显示我的所有模板,即使它们没有与子页面链接并显示两次内容...

谢谢你能帮我解决这个问题,对不起我的英语不好。

【问题讨论】:

    标签: php html wordpress templates parent-child


    【解决方案1】:

    因此,您需要一个“父页面”,它像块一样在“父页面”本身中显示所有“子页面内容”

    将此添加到您的父模板文件中,

    `<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;
    ?>`
    

    这应该将子页面带到父页面,这里我将使用像这样的模板文件“template-introduction.php”,我将添加“introduction”作为模板名称。 这是假设您有不同的子页面模板。

    我没有对此进行测试,理论上这应该可以满足您的需求。

    【讨论】:

    • 我试过了,它奏效了!非常感谢您的帮助,我也了解了代码的结构!
    • 不客气...如果有任何其他问题,请告诉我。
    猜你喜欢
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多