wordpress加密文章详情页显示摘要

在加密文章详情页面显示摘要,我们同样面临与列表页相同的问题:WordPress默认会隐藏加密文章的内容,包括摘要。但是,在详情页面,我们可能希望展示一个非敏感的摘要,以提示用户文章的大致内容,同时要求输入密码。

在主题的single.php或者对应的模板文件中,找到你想显示摘要的位置,然后使用以下代码:

 <?php
        // 如果是加密文章,并且要求输入密码,则显示自定义摘要
        if ( post_password_required() ) :
            global $post;
            if ( ! empty( $post->post_excerpt ) ) {
                $the_excerpt = $post->post_excerpt;
            } else {
                // 生成自动摘要
                $the_excerpt = wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ), 30, '...' );
            }
            ?>
            <div class="protected-excerpt">
                <?php echo $the_excerpt; ?>
            </div>
        <?php endif; ?>