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

如何让WordPress私密文章的/testimonial/伪子页面保持可见?

解决方案:让私密活动的/testimonial/伪子页面保持公开可见

核心思路

在WordPress请求处理阶段,单独拦截/testimonial/伪子页面的请求,绕过父活动文章的私密权限检查,手动加载对应模板并传递活动数据,无需额外添加postmeta避免与标准post_status冲突。

具体实现代码

将以下代码添加到主题的functions.php文件或自定义插件中:

add_action('template_redirect', 'allow_testimonial_subpage_for_private_events');
function allow_testimonial_subpage_for_private_events() {
    global $wp;
    $event_cpt_slug = 'event'; // 替换为你的活动自定义文章类型slug
    // 匹配URL结构:/{活动CPT slug}/{活动slug}/testimonial/
    $pattern = '/' . preg_quote($event_cpt_slug, '/') . '\/([^\/]+)\/testimonial\/?$/';

    if (preg_match($pattern, $wp->request, $matches)) {
        $event_slug = $matches[1];
        // 获取对应活动文章(包含私密状态)
        $event = get_page_by_path($event_slug, OBJECT, $event_cpt_slug);

        if ($event) {
            // 绕过规范URL重定向和私密文章权限拦截
            remove_action('template_redirect', 'redirect_canonical');
            // 初始化全局post数据,确保模板能获取活动信息
            global $post;
            $post = $event;
            setup_postdata($post);

            // 加载你的testimonial子页面模板
            // 替换为你实际的模板文件标识,比如模板文件是single-event-testimonial.php
            get_template_part('single-event', 'testimonial');
            exit;
        }
    }
}

关键细节说明

  1. URL匹配逻辑:代码通过正则匹配你的伪子页面URL结构,需确保$event_cpt_slug与活动自定义文章类型的slug一致。
  2. 获取私密文章:get_page_by_path函数默认支持获取所有状态的文章,无需额外参数,直接通过slug即可定位到私密活动。
  3. 模板数据初始化:手动设置全局$post并调用setup_postdata,解决你之前在模板中获取信息返回null的问题,模板内可正常使用the_title()、get_post_meta()等函数。
  4. 权限隔离:父活动页面仍保持私密状态,只有登录用户可访问;仅/testimonial/子页面对公众开放,不会破坏原生权限逻辑。

后续操作

  • 确保你的testimonial模板文件(如single-event-testimonial.php)已存在,模板内可正常渲染评论表单及活动关联内容。
  • 测试私密活动的/testimonial/页面,确认公众可正常访问,而活动主页面仍需登录权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:43:31