WordPress:无需输入密码在归档页显示密码保护文章的标题及自定义字段副标题
解决WordPress归档页无需密码显示加密文章标题及自定义副标题
WordPress默认会对密码保护的文章在归档页显示密码验证提示,无法直接看到标题和自定义副标题。可以通过添加以下代码实现需求:
方法1:单独处理标题与自定义副标题
1. 强制在归档页显示加密文章标题
将以下代码添加到主题的functions.php文件或自定义功能插件中:
add_filter('the_title', 'show_protected_title_on_archives', 10, 2); function show_protected_title_on_archives($title, $post_id) { $post = get_post($post_id); if (is_archive() && post_password_required($post)) { $title = $post->post_title; } return $title; }
2. 显示自定义副标题(以字段键subtitle为例)
如果你的自定义副标题字段键是subtitle,添加以下代码:
add_action('archive_after_title', 'output_protected_subtitle'); function output_protected_subtitle() { global $post; if (is_archive() && post_password_required($post)) { $subtitle = get_post_meta($post->ID, 'subtitle', true); if (!empty($subtitle)) { echo '<div class="archive-subtitle">' . esc_html($subtitle) . '</div>'; } } }
随后在Elementor归档模板的标题下方,添加「自定义HTML」模块,写入<?php do_action('archive_after_title'); ?>(需确保Elementor允许PHP代码执行,或在主题归档模板对应位置添加该代码)。
方法2:直接替换归档页加密文章的内容块
如果希望直接替换归档页中加密文章的默认提示内容,显示标题、副标题并保留跳转入口,使用以下代码:
add_filter('the_content', 'rewrite_protected_archive_content', 10, 1); function rewrite_protected_archive_content($content) { global $post; if (is_archive() && post_password_required($post)) { $subtitle = get_post_meta($post->ID, 'subtitle', true); $custom_content = '<h3 class="archive-post-title">' . esc_html($post->post_title) . '</h3>'; if (!empty($subtitle)) { $custom_content .= '<p class="archive-post-subtitle">' . esc_html($subtitle) . '</p>'; } $custom_content .= '<p class="view-full-content"><a href="' . get_permalink($post->ID) . '">点击输入密码查看完整内容</a></p>'; $content = $custom_content; } return $content; }
注意事项
- 将代码中的
subtitle替换为你实际使用的自定义字段键名 - 推荐使用自定义功能插件添加代码,避免主题更新导致代码丢失
- 若使用Elementor,需确保模板中对应位置调用了
the_title()或the_content(),否则代码无法生效
内容的提问来源于stack exchange,提问作者Bilawal Zafar
相关产品推荐
相关产品推荐

