WordPress中get_template_part() 函数使用方法

  • 2020-12-31 20:41:09
  • 1,671 次阅读
  • 稿源:天马行空

wordpress制作网站,在实现独立移动站跳转时,用到了get_template_part() 函数加载手机模版,如果对这个函数不是很清楚,就要到网上搜索一下,详细了解此函数怎么使用。

在wordpress 3.0 以后就有了get_template_part() 函数 ,应该是为文章呈现形式,提供更为多样化的选择而给出的新功能。

Twenty Eleven 主题index.php文件实例:

<?php if ( have_posts() ) : ?>
	<?php twentyeleven_content_nav( 'nav-above' ); ?>
	<?php /* Start the Loop 在循环中使用以调用不同类型的文章 */ ?>
	<?php while ( have_posts() ) : the_post(); ?>
		<?php get_template_part( 'content', get_post_format() ); ?>
	<?php endwhile; ?>
............................
<?php endif; ?>

描述:

加载一个制定的模板到另一个模板里面(不同于包含header,sidebar,footer).

使得一个主题使用子模板来实现代码段重用变得简单

用于在模板中包含指定的模板文件,只需用指定参数slug和name就可以包含文件{slug}-{name}.php,最重要的功能是如果没有这个文件就包含没有{name}的.php文件文件

使用方法:

<?php get_template_part( $slug, $name ) ?>

参数:

$slug (必须) 通用的模板名

$name (可选) 指定的模板名

示例:

使用 loop.php 在子主题里面

假设主题文件夹wp-content/themes下父主题是twentyten子主题twentytenchild,那么下面的代码:

<?php get_template_part( 'loop', 'index' ); ?>

php 的require()函数将按下面优先级包含文件

1. wp-content/themes/twentytenchild/loop-index.php
2. wp-content/themes/twentytenchild/loop.php
3. wp-content/themes/twentyten/loop-index.php
4. wp-content/themes/twentyten/loop.php

导航(这个例子很烂,但却是另一种使用思路)使用通用的nav.php文件给主题添加导航条:

<?php get_template_part( 'nav' );           // Navigation bar (nav.php) ?>
<?php get_template_part( 'nav', '2' );      // Navigation bar #2 (nav-2.php) ?>
<?php get_template_part( 'nav', 'single' ); // Navigation bar to use in single pages (nav-single.php) ?>

喜欢 2

文章评论 (0)

表情

大眼 可爱 大笑 坏笑 害羞 发怒 折磨 快哭了 大哭 白眼 晕 流汗 困 腼腆 惊讶 憨笑 色 得意 骷髅 囧 睡觉 眨眼 亲亲 疑问 闭嘴 难过 淡定 抗议 鄙视 猪头