For example, if I write some code (e.d. add a custom post type or something) in my theme’s functions.php, it works fine. If I move it to a new file, then include()
the file in my theme’s functions.php file, it no longer works (but debug code using error_log()
still works.
e.g.
Here’s functions.php:
<?php
// ###### functions.php ######
error_log("fu_debug: Including the post type.");
add_action('init', 'fu_create_project_post_type');
function fu_create_project_post_type() {
error_log("fu_debug: create project post type");
register_post_type( 'fu_project',
array(
'labels' => array(
'name' => __( 'Projects' ),
'singular_name' => __( 'Project' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'projects'),
)
);
}
?>
That works fine. Now, if I change functions.php to this:
<?php
// ###### functions.php ######
include "newfile.php";
?>
and put the code inside newfile.php like this:
<?php
// ###### newfile.php ######
error_log("fu_debug: Including the post type.");
add_action('init', 'fu_create_project_post_type');
function fu_create_project_post_type() {
error_log("fu_debug: create project post type");
register_post_type( 'fu_project',
array(
'labels' => array(
'name' => __( 'Projects' ),
'singular_name' => __( 'Project' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'projects'),
)
);
}
?>
the code no longer works, but the error_log() message still shows up in the logs.
Why does the error message still work, but the wordpress code not?
2 Answers
When including files in functions.php
, you need to reference the correct filepath, using get_template_directory()
:
include( get_template_directory() . '/newfile.php' );