首页 视频课程 主题开发课程第02章、开发实例 WordPress入门实例:标签页面制件方法

WordPress入门实例:标签页面制件方法

2023-06-11 / 511阅

WordPress入门实例:标签页面制件方法

标签页面是 WordPress 中的一个重要页面,可以方便地浏览与某个标签有关的所有文章。本文将介绍如何制作一个标签页面,提供示例代码,并使用 markdown 进行排版。

1. 创建标签页面模板

在 WordPress 主题文件夹中的 page.php 文件夹下创建一个名为 tag.php 的文件。这个文件将作为标签页面的模板。

<?php
/**
 * The template for displaying tag pages
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#tag
 *
 * @package WordPress
 * @subpackage Twenty_Twenty
 * @since Twenty Twenty 1.0
 */

get_header();
?>

    <main id="site-content" role="main">

        <?php if ( have_posts() ) : ?>

            <header class="page-header alignwide">
                <?php
                the_archive_title( '<h1 class="page-title">', '</h1>' );
                the_archive_description( '<div class="archive-description">', '</div>' );
                ?>
            </header><!-- .page-header -->

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

            <?php twenty_twenty_the_posts_navigation(); ?>

        <?php else : ?>

            <?php get_template_part( 'template-parts/content', 'none' ); ?>

        <?php endif; ?>

    </main><!-- #site-content -->

<?php get_footer(); ?> 

2. 编写标签查询函数

在主题的 functions.php 文件中添加以下代码来查询与某个特定标签相关的文章。

/**
 * Modify the main query for tag pages
 *
 * @param WP_Query $query
 */
function my_custom_tag_page_query( $query ) {
    if ( $query->is_tag() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', 10 );
    }
}
add_action( 'pre_get_posts', 'my_custom_tag_page_query' ); 

这个函数将查询与该页面标签相关的文章,每页最多显示 10 篇文章。

3. 显示标签页标题和文章列表

tag.php 文件中,使用 WordPress 的 the_archive_titlethe_archive_description 函数来显示标签页的标题和描述,使用 have_postswhile 循环来显示文章列表。

<header class="page-header alignwide">
    <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); ?>
    <?php the_archive_description( '<div class="archive-description">', '</div>' ); ?>
</header><!-- .page-header -->

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

<?php twenty_twenty_the_posts_navigation(); ?> 

4. 展示标签页

标签页面创建完成后,在 WordPress 后台可直接通过在菜单中添加一个“自定义链接”,链接到这个标签页面。

到这里,我们已经完成了一个简单的标签页面的制作。可以根据实际情况对其进行扩展和优化。

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录