You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义文章页调取与标题同名标签下内容的实现问题

single-{custom-post-type}.php 关联标签内容实现方案

以下代码可直接放入你的自定义文章类型单页模板中使用:

<?php
// 主循环:输出当前自定义文章的标题与内容
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        the_title( '<h1>', '</h1>' );
        the_content();
    endwhile;
endif;

// -------------- 关联标签内容查询逻辑 --------------
// 获取当前文章标题,去除首尾冗余空格
$current_title = trim( get_the_title() );

// 按名称匹配标签,默认使用WordPress自带的post_tag标签分类法
// 如果你使用的是自定义标签分类法,替换下方taxonomy参数值为你的分类法别名即可
$matched_tags = get_terms( array(
    'taxonomy' => 'post_tag',
    'name' => $current_title,
    'hide_empty' => true,
    'number' => 1
) );

// 匹配到对应标签后执行关联内容查询
if ( !empty( $matched_tags ) ) :
    $tag_id = $matched_tags[0]->term_id;

    // 自定义查询:拉取所有绑定该标签的已发布内容
    $related_posts = new WP_Query( array(
        'post_type' => 'any', // 可修改为指定文章类型数组,比如 array('post', '你的自定义文章类型别名')
        'posts_per_page' => -1, // 输出所有匹配内容,可自定义数字限制展示数量
        'tax_query' => array(
            array(
                'taxonomy' => 'post_tag',
                'field' => 'term_id',
                'terms' => $tag_id
            )
        ),
        'post_status' => 'publish',
        'post__not_in' => array( get_the_ID() ) // 排除当前文章,避免重复展示,不需要可删除该行
    ) );

    if ( $related_posts->have_posts() ) :
?>
        <h3>相关内容列表</h3>
        <ul>
        <?php while ( $related_posts->have_posts() ) : $related_posts->the_post(); ?>
            <li>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <!-- 可按需扩展添加缩略图、摘要、发布时间等字段 -->
            </li>
        <?php endwhile; ?>
        </ul>
<?php
    endif;
    // 必须执行重置操作,避免污染全局主查询
    wp_reset_postdata();
endif;
?>

配置说明

  • 如果你使用自定义标签分类法,需要同步修改代码中两处taxonomy参数的取值
  • post_type设置为any代表查询所有公开的文章类型,可自行修改为指定的文章类型缩小查询范围
  • 列表的输出样式和字段可根据你的前端需求自行调整
    内容的提问来源于stack exchange,提问作者Spyker55
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:24:01