3

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?

3
  • 2
    It should work. I break my functions.php up like that all the time, and I tested the code you posted. It works fine, though there are potential problems with defining a post type in a theme.
    – s_ha_dum
    Jul 14, 2013 at 1:30
  • 1
    Why don't you use locate_template()?
    – kaiser
    Jul 14, 2013 at 1:58
  • 2
    I'd use a functionality plugin instead because post type should not depend on theme.
    – JMau
    Jul 14, 2013 at 12:38

2 Answers 2

5

When including files in functions.php, you need to reference the correct filepath, using get_template_directory():

include( get_template_directory() . '/newfile.php' );
1
  • Aah! Maybe that's it! Let me try that out...
    – trusktr
    Jan 19, 2014 at 5:34
0

This will point back at PARENT theme:
require_once( get_template_directory() . '/include/myscript.php' );

If using a CHILD theme (and you should!), use this:
require_once( get_stylesheet_directory() . '/include/myscript.php' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.