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

如何在首页文章循环中修改指定自定义文章类型的‘Read more’文本

针对自定义文章类型修改“Read more”文本的两种方法

这个需求其实很好实现,咱们可以通过两种方式来搞定,根据你的模板结构选合适的就行:

方法一:在循环内直接判断文章类型输出

如果你的首页模板里已经写了循环代码,直接在输出“Read more”的地方加个判断就行,代码示例如下:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <!-- 这里放你的文章标题、摘要等现有代码 -->
    
    <?php
    // 替换成你自己的自定义文章类型slug(比如portfolio、product这类)
    $custom_post_type = 'your_custom_post_type';
    // 根据文章类型设置不同的文本
    $read_more_text = ( get_post_type() === $custom_post_type ) ? '查看完整内容' : 'Read more';
    ?>
    
    <a href="<?php the_permalink(); ?>" class="read-more-btn">
        <?php echo esc_html( $read_more_text ); ?>
    </a>

<?php endwhile; endif; ?>

说明:

  • 把your_custom_post_type替换成你实际的自定义文章类型标识(可以在后台自定义文章类型的设置里找到,或者用get_post_types()函数查看所有可用类型)
  • esc_html()是为了安全转义文本,避免潜在的XSS风险,建议加上

方法二:用过滤器全局替换(无需修改循环代码)

如果你不想改动模板里的循环代码,或者想让所有地方的Read more文本都按文章类型区分,可以用WordPress的过滤器函数,把下面的代码加到主题的functions.php里:

// 针对the_content()生成的Read more链接
add_filter( 'the_content_more_link', 'custom_read_more_by_post_type', 10, 2 );
function custom_read_more_by_post_type( $more_link, $more_text ) {
    $custom_post_type = 'your_custom_post_type';
    if ( get_post_type() === $custom_post_type ) {
        // 替换成你想要的自定义文本
        $new_text = '查看详情';
        $more_link = str_replace( $more_text, $new_text, $more_link );
    }
    return $more_link;
}

// 针对the_excerpt()生成的Read more文本(如果你的主题用了摘要)
add_filter( 'excerpt_more', 'custom_excerpt_more_by_post_type' );
function custom_excerpt_more_by_post_type( $more ) {
    $custom_post_type = 'your_custom_post_type';
    if ( get_post_type() === $custom_post_type ) {
        return ' <a href="'. get_permalink() .'">查看完整内容</a>';
    }
    return $more;
}

说明:

  • 这个方法会全局生效,不管是首页还是其他页面,只要是对应自定义文章类型的内容,Read more文本都会被替换
  • 同样要记得替换your_custom_post_type为实际的类型slug

内容的提问来源于stack exchange,提问作者X9DESIGN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:08:51