第 1 步:
我建议使用首页模板中的get_template_part() 函数将布局分成几个部分。这样做的好处是您可以简单地在任何页面模板中调用您需要的任何布局部分,如下所示:get_template_part('testimonials');。如果需要,您甚至可以在页眉和页脚中使用它们。
在您的情况下,我假设有 3 个模板部分:关于我们、功能和推荐。您将需要创建 3 个 PHP 文件,其中包含这 3 个部分的所有代码。 PHP 文件需要位于模板的根文件夹中。 PHP 文件显然可以根据需要使用 PHP,但主要思想是您的 HTML 代码为该部分或“模板部分”将放置在它自己的 PHP 文件中。如果您需要从 wordpress 中提取帖子,或执行数据库查询以生成该部分的内容,您可以在它自己的自包含 PHP 文件中为每个模板部分单独执行此操作。出于本示例的目的,我们假设您已为模板部分调用了 PHP 文件 about_us_part.php、features_part.php 和 testimonials_part.php。
创建 3 个 PHP 文件后,确保将它们放置在模板根目录中,您只需将以下代码行放置在您希望特定部分或“模板部分”出现在 Wordpress 页面模板中的任何位置。像这样:
<?php get_template_part( 'about_us_part' ); // About Us (about_us_part.php) ?>
<?php get_template_part( 'features_part' ); // Features (features_part.php) ?>
<?php get_template_part( 'testimonials_part' ); // Testimonials (testimonials_part.php) ?>
基本上,get_template_part( '{slug}' ); 在模板根目录中搜索与{slug}.php 匹配的文件名。所以你可以随意命名它,但是如果没有找到匹配的 PHP 文件,显然什么都不会出现。 get_template_part() 的另一个选项允许您为模板部分指定名称。但是它是可选的,不是必需的,您可以像这样使用它:
<?php get_template_part( 'about_us_part', 'about-us' ); // About Us (about_us_part.php) ?>
<?php get_template_part( 'features_part', 'features' ); // Features (features_part.php) ?>
<?php get_template_part( 'testimonials_part', 'testimonials' ); // Testimonials (testimonials_part.php) ?>
您可以在此处阅读有关 Wordpress 法典中的 get_template_part() 的更多信息:
http://codex.wordpress.org/Function_Reference/get_template_part
第 2 步:
现在假设您希望允许用户使用简码显示这些模板部分,您需要在您的 functions.php 文件中赋予他们该功能。例如,假设我们想为上面的 3 个模板部分中的每一个创建 3 个简码。您可以使用 Wordpress Shortcode API 轻松完成。您将以下代码添加到您的 functions.php 文件中:
[about_us]
function themeprefix_about_us_shortcode( $attr ) {
ob_start(); // Start output buffer
get_template_part( 'about_us_part' ); //Get about_us_part.php
return ob_get_clean(); //Clear output buffer
}
add_shortcode( 'about_us', 'themeprefix_about_us_shortcode' );
一旦该函数在您的functions.php 文件中,以及匹配的add_shortcode() 函数,用户就可以使用简码[about_us] 调出“关于我们”部分。 add_shortcode() 函数的两个部分是短代码名称,以及为短代码生成内容的函数。像这样:add_shortcode( '{shortcode name}', '{shortcode function}' );
您需要为其他 2 个短代码再创建 2 个:
[功能]
function themeprefix_features_shortcode( $attr ) {
ob_start(); // Start output buffer
get_template_part( 'features_part' ); //Get features_part.php
return ob_get_clean(); //Clear output buffer
}
add_shortcode( 'features', 'themeprefix_features_shortcode' );
[推荐]
function themeprefix_testimonials_shortcode( $attr ) {
ob_start(); // Start output buffer
get_template_part( 'testimonials_part' ); //Get testimonials_part.php
return ob_get_clean(); //Clear output buffer
}
add_shortcode( 'testimonials', 'themeprefix_testimonials_shortcode' );
注意:我把“themeprefix”放在每个函数的前面。我建议将其替换为您的主题名称,或者您可能在主题函数名称前面使用的任何前缀。然而函数名可以是任何你想要的,只要确保将你的add_shortcode()更新为新的函数名。
您可以在此处阅读有关 Wordpress 法典中 add_shortcode() 的更多信息:
http://codex.wordpress.org/Function_Reference/add_shortcode
另外,我建议阅读 codex 中的 Shortcode API 页面,了解如何将参数添加到您的简码:
http://codex.wordpress.org/Shortcode_API