首页 问答 正文

wordpress中如何添加自定义页面模板?

注册会员 / 悠然自学 / 2023-06-11/ 浏览 210 次

  1. 首先,在 WordPress 主题的根目录中创建一个新的 PHP 文件,例如“custom-template.php”。
  2. 在该文件开头添加以下代码:
<?php
/**
 * Template Name: Custom Template
 */
?> 

其中,“Custom Template”是你想要命名的自定义页面模板的名称。

  1. 在文件中添加 HTML 和 PHP 代码,来构建自定义页面模板的样式和功能。

  2. 将文件保存到 WordPress 主题文件夹的“/wp-content/themes/your-theme-name/”目录中。

  3. 在 WordPress 后台页面的“页面”部分,创建一个新页面。

  4. 在“页面属性”>“模板”下拉菜单中选择你创建的自定义页面模板的名称,并保存页面。

示例代码:

<?php
/**
 * Template Name: Custom Template
 */

get_header(); ?>

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

        <?php
        // Start the Loop.
        while ( have_posts() ) :
            the_post();

            // Include the page content template.
            get_template_part( 'template-parts/content', 'page' );

        endwhile; // End the loop.
        ?>

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

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

此代码创建了一个名为“Custom Template”的自定义页面模板,然后加载了一个顶部导航栏、主体区域、边栏和底部区域。其中,在 while 循环中的“template-parts/content-page.php”文件会加载所选页面的内容。

大家谈论
    我的见解