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

WordPress技术问询:自定义header判断及自定义文章类型端点页面识别

嘿,针对你遇到的两个WordPress开发场景问题,我来给你梳理实用的解决方案:

问题1:判断是否使用了自定义header.php的方案

WordPress并没有原生的条件标签直接实现这个判断,但我们可以通过钩子或者模板路径检测来搞定:

  • 方法1:利用get_header钩子跟踪
    在主题的functions.php里添加这段代码,记录是否加载了自定义header:

    $custom_header_used = false;
    
    add_action('get_header', function($name) {
        global $custom_header_used;
        // 如果指定了自定义header名称,或者加载的不是默认header.php
        if (!empty($name) || locate_template("header-$name.php") !== locate_template('header.php')) {
            $custom_header_used = true;
        }
    });
    

    之后在任意模板文件里,你可以通过global $custom_header_used;调用这个变量,当它为true时,就说明当前使用的是自定义header。

  • 方法2:直接检查加载的header文件路径
    写一个自定义函数来对比当前加载的header和默认header的路径:

    function is_custom_header_used() {
        $default_header = locate_template('header.php');
        // 获取当前实际加载的header模板路径
        $current_header = get_query_var('header_template', 'header.php');
        $current_header_path = locate_template($current_header);
        
        return $current_header_path !== $default_header;
    }
    

    用的时候直接写if (is_custom_header_used()) { /* 自定义header逻辑 */ }就行。

问题2:自定义文章类型campaigns中判断无endpoint的主页面

既然你已经通过add_rewrite_endpoint添加了三个子页面(overview/preview/analytics),我们可以通过检查这些endpoint对应的查询变量是否存在来判断当前是否是主页面(campaigns/文章标题/):

首先确保你的endpoint注册是正确的(如果还没写,参考这段):

add_action('init', function() {
    // 为campaigns单页注册三个endpoint
    add_rewrite_endpoint('overview', EP_PERMALINK);
    add_rewrite_endpoint('preview', EP_PERMALINK);
    add_rewrite_endpoint('analytics', EP_PERMALINK);
});

注意:写完这段后,一定要去WordPress后台的「设置→固定链接」页面点击保存,刷新rewrite规则,否则新的endpoint不会生效。

然后在single-campaigns.php里,用这段条件判断来识别主页面:

if (is_singular('campaigns')) {
    // 获取三个endpoint的查询变量值,不存在则返回false
    $has_overview = get_query_var('overview', false);
    $has_preview = get_query_var('preview', false);
    $has_analytics = get_query_var('analytics', false);
    
    // 当三个endpoint都不存在时,就是你要的主页面
    if (!$has_overview && !$has_preview && !$has_analytics) {
        // 这里写主页面的逻辑,比如加载独立模板
        get_template_part('template-parts/campaign-main');
    } else {
        // 处理其他三个子页面的逻辑
        if ($has_overview) {
            get_template_part('template-parts/campaign-overview');
        } elseif ($has_preview) {
            get_template_part('template-parts/campaign-preview');
        } elseif ($has_analytics) {
            get_template_part('template-parts/campaign-analytics');
        }
    }
}

也可以用更简洁的方式,直接检查$wp_query的查询变量:

global $wp_query;
if (is_singular('campaigns') && !isset($wp_query->query_vars['overview']) && !isset($wp_query->query_vars['preview']) && !isset($wp_query->query_vars['analytics'])) {
    // 主页面逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:51:22