WordPress get_template_part 用法详解:解决 content 报错问题

WordPress 主题开发过程中,get_template_part() 是一个非常常用的函数,用来拆分和重用模板文件。但很多开发者在使用过程中,经常遇到 Call to undefined function content() 的报错。这类错误通常不是 WordPress 的 bug,而是模板结构或命名方式出了问题。

什么是 get_template_part()?

get_template_part() 是 WordPress 推荐的模板拆分方式,它能在不重复代码的前提下,调用指定的模板部分。常用于加载内容区、页眉页脚侧边栏等。

最常见的写法:

get_template_part( ‘template-parts/content’, get_post_type() );

这段代码的作用是:根据当前文章类型,动态加载如 template-parts/content-post.php 或 template-parts/content-page.php 文件。

content() 报错的原因是什么?

报错一般是这样的:Fatal error: Uncaught Error: Call to undefined function content()

大多数时候,这并不是 get_template_part() 自身的问题,而是你在 content.php 文件里直接写了 <?php content(); ?>,但是 content() 这个函数根本不存在。

在WordPress 主题中,content.php 是一个“内容模板”,并不是调用 content() 函数。

正确的结构应该怎么写?

建议采用如下结构来组织模板文件:

主模板文件:index.php 或 archive.php

<?php
while ( have_posts() ) : the_post();
get_template_part( ‘template-parts/content’, get_post_type() );
endwhile;
?>

内容模板文件:如 template-parts/content-post.php

<article id=”post-<?php the_ID(); ?>” <?php post_class(); ?>>
<header class=”entry-header”>
<h2 class=”entry-title”><?php the_title(); ?></h2>
</header>

<div class=”entry-content”>
<?php the_content(); ?>
</div>
</article>

重点是:不要在这些模板中写 content(),因为 WordPress 并没有这个函数。

模板结构命名建议

content.php:默认内容模板

content-post.php:文章类型的模板

content-page.php:页面类型的模板

content-product.php:WooCommerce 产品模板

WordPress 会优先加载带有后缀的版本,如果不存在,则回退到 content.php。

如果想传递变量怎么办?

get_template_part() 默认不支持直接传值。想传值可以使用以下新方法(WordPress 5.5 及以上):

get_template_part( ‘template-parts/content’, ‘custom’, array( ‘custom_class’ => ‘highlight’ ) );

然后在模板中接收:

<div class=”<?php echo esc_attr( $args[‘custom_class’] ?? ” ); ?>”>

</div>

小结

使用 get_template_part() 的时候,记住以下几点:

文件名叫 content-xxx.php,而不是调用一个 content() 函数

文件中直接写结构,而不是定义函数

按照模板层级命名,WordPress 会自动匹配

WordPress 5.5 后可以用 $args 参数传值,更灵活

这不光能解决报错问题,还能让你的主题代码更清晰、更模块化。

最近更新

Leave a Reply

您的电子邮箱地址不会被公开。 必填项已用 * 标注