创建自定义文章类型后,例如商品类型,一般需要新建一个页面用于介绍所有商品以及一个模版页面用于显示每个商品详细信息。

可以在 Page 页面中新建一个页面用于介绍所有商品,那如何指定商品详情页的模版呢?

设置自定义文章类型的模版

其实 Page 页面本质上也是一种文章类型,可以在后台编辑页面时查看到 Post ID

Page ID

以下指定模版的功能是 WordPress 4.7 之后才开始增加的。可以在 wp-content/themes/your-themes/ 下创建默认的模版文件,并指定该模版作用的文章类型或页面

<?php
/*
Template Name: product
Template Post Type: post, page, product
*/

完整的模版示例:

<?php 
/*
 * Template Name: product
 * Template Post Type: post, page, product   
 */ 
get_header();
?>

<div class="container pt-5 pb-5">
    <?php if (has_post_thumbnail()):?>
      <img src="<?php the_post_thumbnail_url('largest');?>" class="img-fluid">
    <?php endif;?>
    <?php if (have_posts()) : while (have_posts()) : the_post();?>
        <?php the_content();?>
    <?php endwhile; endif;?>
</div>

<?php get_footer();?>

官方文档: