WordPress如何自定义文章详情页模板

文 / @WordPress主题

WordPress允许用户自定义文章详情页的模板。要自定义文章详情页的模板,首先需要在主题文件夹中创建一个名为single.php的文件。如果主题文件夹中已经有一个名为single.php的文件,则可以直接在该文件中进行自定义。

为了确保模板能够正常工作,建议在开始自定义之前先备份原有的single.php文件。然后,可以通过以下步骤来自定义文章详情页的模板:

  1. 打开single.php文件,然后将其中的内容替换为以下代码:
<?php
/*
Template Name: Single Post
*/

get_header();
?>

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

<?php
while ( have_posts() ) :
the_post();

get_template_part( 'template-parts/content', get_post_type() );

the_post_navigation();

// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;

endwhile; // End of the loop.
?>

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

<?php
get_sidebar();
get_footer();

  1. template-parts文件夹中创建一个名为content-single.php的文件。
  2. 将以下代码添加到content-single.php文件中:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header><!-- .entry-header -->

<?php if ( has_post_thumbnail() ) : ?>
<div class="post-thumbnail">
<?php the_post_thumbnail(); ?>
</div><!-- .post-thumbnail -->
<?php endif; ?>

接下来,可以使用以下代码来显示文章内容:

<div class="entry-content">
<?php
the_content();

wp_link_pages( array(
'before' => '<div class="page-links">' . __( 'Pages:', 'your-theme' ),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->

最后,可以使用以下代码来显示文章元信息(例如作者、发布日期和分类):

<footer class="entry-footer">
<?php your_theme_entry_footer(); ?>
</footer><!-- .entry-footer -->

完成上述步骤后,就可以保存文件并查看自定义的文章详情页模板。如果需要进行进一步的自定义,可以继续修改content-single.php文件,并根据自己的需求添加或修改代码。

如果您想要添加更多的内容到文章详情页的模板中,可以继续修改content-single.php文件。例如,可以添加文章的分类和标签,以便用户更容易地找到相关文章:

<footer class="entry-footer">
<?php your_theme_entry_footer(); ?>
</footer><!-- .entry-footer -->

<?php
// Get the categories and tags for the post.
$categories = get_the_category();
$tags = get_the_tags();
?>

<?php if ( $categories || $tags ) : ?>
<div class="entry-meta">
<?php if ( $categories ) : ?>
<span class="cat-links">
<?php
foreach ( $categories as $category ) {
echo '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a> ';
}
?>

</span><!-- .cat-links -->
<?php endif; ?>

<?php if ( $tags ) : ?>
<span class="tag-links">
<?php
foreach ( $tags as $tag ) {
echo '<a href="' . esc_url( get_tag_link( $tag->term_id ) ) . '">' . esc_html( $tag->name ) . '</a> ';
}
?>

</span><!-- .tag-links -->
<?php endif; ?>
</div><!-- .entry-meta -->
<?php endif; ?>

可以根据自己的需求,添加更多的内容或修改上述代码,以实现更多的自定义。例如,可以添加文章的作者信息,或者添加文章的相关文章等。

总之,自定义文章详情页的模板需要结合主题的特定代码和功能,并结合您的需求进行调整。

添加UTHEME为好友
扫码添加UTHEME微信为好友
· 分享WordPress相关技术文章,主题上新与优惠动态早知道。
· 微信端最大WordPress社群,限时免费入群。