WordPress主题functions.php语法报错,添加自定义代码失败求助
Hey there, let's break down why you're hitting that syntax error and how to fix it!
What's Causing the Error?
That error message means PHP got confused about where your add_filter() call belongs. It almost always happens for one of two reasons:
- You placed the
add_filter()line inside another function or class (instead of the global scope offunctions.php), so PHP was expecting a function definition (T_FUNCTION) instead of a function call. - There's a tiny syntax mistake in the code right before this snippet—like an unclosed curly brace
}or a missing semicolon—which throws off PHP's parser entirely.
Step-by-Step Fixes
Move your code to the global scope
Make sure youradd_filter()and its paired function aren't nested inside any other functions, conditionals, or classes infunctions.php. They should sit directly at the top level of the file (after any existing global code).Check for unclosed syntax before your code
Scroll up infunctions.phpand scan for any open{that doesn't have a matching}, or lines ending without a semicolon. Even one missing character can break the entire file.Use this cleaned-up, working code
Here's your code with reliability improvements, placed correctly in the global scope:// Add this directly in your theme's functions.php (not inside another function) add_filter( 'tribe_events_pre_get_posts', 'redirect_from_events' ); function redirect_from_events( $query ) { // Skip if user is already logged in if ( is_user_logged_in() ) { return $query; } // Only target the main Events Calendar query if ( ! $query->is_main_query() || ! $query->get( 'eventDisplay' ) ) { return $query; } // Fetch the target page efficiently $target_page = get_posts( array( 'post_type' => 'page', 'name' => 'logged-in-users-only', 'numberposts' => 1, // Limit to 1 result for speed 'post_status' => 'publish' // Ensure we only get published pages ) ); // Redirect if we found the page if ( ! empty( $target_page ) ) { wp_redirect( get_permalink( $target_page[0]->ID ) ); exit; // Critical: Stop execution after redirect } else { // Fallback: Redirect to login page if target page doesn't exist wp_redirect( wp_login_url() ); exit; } return $query; }A couple key tweaks here:
- Added
numberposts => 1to makeget_posts()run faster. - Added
exit;after redirects—this is mandatory, otherwise WordPress might ignore the redirect. - Added
post_status => 'publish'to avoid fetching draft or private pages.
- Added
Double-Check
After updating functions.php, save the file and test accessing your events page while logged out. The redirect should work without any syntax errors now.
内容的提问来源于stack exchange,提问作者Massi




