You need to enable JavaScript to run this app. WordPress主题开发报unexpected "endif" 语法错误如何修复?
优惠活动
大模型
产品
解决方案
定价
更多

WordPress主题开发报unexpected "endif" 语法错误如何修复?

语法错误核心原因

所有触发报错的判断块,都在if语句的行尾错误添加了分号,直接打断了PHP的替代语法结构:

  • PHP 模板中使用 if(): ... endif;、while(): ... endwhile; 这类替代语法时,开头的判断行必须以冒号结尾,不能加分号
  • 当前代码里写的 if (xxx); 会让PHP直接判定这个if是一个没有执行体的空语句,到分号位置就结束了这个判断块
  • 后续跟的函数定义、循环、闭合用的endif 全都成了脱离结构的游离代码,解析器找不到和endif匹配的if块,就会抛出“unexpected token "endif", expecting end of file”的报错
  • 之前调整endwhile写法没用,是因为错误根源根本不在循环的闭合逻辑,而在更靠前的if行的符号错误。
逐文件修复方案

1. function.php 修复

把错误的 if (! function_exists('setup')); 行尾的分号替换为冒号,修复后完整代码:

<?php
function register_nav(){
    register_nav_menus(
        array(
            'header' => 'Header'
        )
    );

    register_nav_menus(
        array(
            'footer' => 'Footer'
        )
    );

    register_nav_menus(
        array(
            '404' => '404'
        )
    );
}

// 原行尾的分号改为冒号,匹配后续的endif
if (! function_exists('setup')):
    function setup(){
        register_nav();
        add_theme_support('post-thumbnails');
        add_image_size('team', 475, 475, array('center','center'));
    }
endif;

function scripts_header(){
    wp_enqueue_style('init', get_stylesheet_uri());
}

function scripts_footer(){
    // wp_enqueue_script('init', get_template_directory_uri().'/js/init.js', array('jquery'));
}

add_action('after_setup_theme', 'setup');
add_action('wp_enqueue_scripts', 'scripts_header');
// 原注释行末尾缺失分号,不触发报错但建议补全
//add_action('wp_footer', 'scripts_footer');

2. index.php / page.php 修复

两个文件存在完全相同的错误,把错误的 if (have_posts()); 行尾的分号替换为冒号即可,修复后代码:

<?php
get_header();
// 原行尾的分号改为冒号
if (have_posts()):
    while (have_posts()) :
        the_post();
        the_content();
    endwhile;
endif;
get_footer();
?>
开发注意提示

*使用PHP替代语法写模板时,每一层判断、循环的开头结尾必须严格配对:

  • 冒号开头的结构,必须用对应的 endif/endwhile/endfor 闭合
  • 绝对不要在判断行尾额外加分号,哪怕IDE提示你缺分号——分号在这个位置就是语法错误*

内容的提问来源于stack exchange,提问作者Ashraful Islam Joy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 23:15:03