如何使用WordPress的模板标签 get_header(), get_footer(), 和 get_sidebar() 来包含主题文件?

2024-12-11 137 0

在WordPress中,模板标签 get_header(), get_sidebar(), 和 get_footer() 是用于包含主题中特定部分(如页眉、侧边栏和页脚)的函数。以下是如何使用这些模板标签来包含主题文件的基本步骤:

  1. get_header() - 这个函数用于包含主题的 header.php 文件,它通常包含了网站的标题、导航菜单、以及页眉部分的任何其他内容。

    在你的主题的任何模板文件(如 index.php, page.php, single.php 等)的顶部,你可以调用 get_header() 函数:

    <?php get_header(); ?>
  2. get_sidebar() - 这个函数用于包含主题的 sidebar.php 文件,它通常包含了侧边栏的小工具区域。

    在你的模板文件中,通常在主内容区域旁边,你可以调用 get_sidebar() 函数:

    <?php get_sidebar(); ?>
  3. get_footer() - 这个函数用于包含主题的 footer.php 文件,它通常包含了版权信息、链接到隐私政策页面的链接、以及页脚部分的任何其他内容。

    在你的模板文件的底部,你可以调用 get_footer() 函数:

    <?php get_footer(); ?>

以下是一个示例,展示了如何在 index.php 文件中使用这些模板标签:

<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package Your_Theme_Name
 */

get_header(); ?>

<div id="primary" class="content-area">
    <main id="main" class="site-main">

        <?php
        if ( have_posts() ) :

            if ( is_home() && ! is_front_page() ) :
                ?>
                <header>
                    <h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
                </header>
                <?php
            endif;

            /* Start the Loop */
            while ( have_posts() ) :
                the_post();

                /*
                 * Include the Post-Type-specific template for the content.
                 * If you want to override this in a child theme, then include a file
                 * called content-___.php (where ___ is the Post Type name) and that will be used instead.
                 */
                get_template_part( 'template-parts/content', get_post_type() );

            endwhile;

            the_posts_navigation();

        else :

            get_template_part( 'template-parts/content', 'none' );

        endif;
        ?>

    </main><!-- #main -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

在这个例子中,get_header() 在文档的开始处被调用,get_sidebar() 在主要内容之后被调用,而 get_footer() 在文档的末尾被调用。这些函数确保了页眉、侧边栏和页脚被正确地包含在页面上。

相关文章

如何在WordPress插件中使用ajax?
如何通过WordPress函数创建自定义菜单?
在WordPress主题开发中,如何使用WP_Customize_Manager来自定义主题选项?
如何使用WordPress的filter钩子修改输出内容?
如何使用WordPress的action钩子添加自定义JavaScript?
在WordPress插件中,如何使用自定义表单和nonce字段来增强安全性?