get_template_directory_uri() and other URL tags not working in theme

So, I’m trying to add get_template_directory_uri or bloginfo() to my header.php file to create relative paths for the CSS and JS files in the theme.

E.g.,

    <link rel="stylesheet" href="https://wordpress.stackexchange.com/questions/46261/<?php echo get_template_directory_uri(); ?>/css/style.css">

In theory this should show

    <link rel="stylesheet" href="http://mysite.com/wp-content/themes/myTheme/css/style.css">

Problem is, when I view the <head> tag in source all I see is:

    <link rel="stylesheet" href="https://wordpress.stackexchange.com/css/style.css">

All the other template tags work in my files (get_permalink(), the_title(), etc.), but this one isn’t. echo get_bloginfo('url') Also works.

I was thinking of messing with the wp-config.php file and doing something like:

define('WP_HOME','http://example.com/blog');
define('WP_SITEURL','http://example.com/blog');

…but, I’m not sure if that’s the best practice for rewriting the URL.

Am I missing something?

5 Answers
5

What you have:

 <link rel="stylesheet" href="https://wordpress.stackexchange.com/questions/46261/<?php echo get_template_directory_uri(); ?>/css/style.css">

should work fine. I’ve copied and pasted into my header.php and it worked.

But this is not how you should be including css or javascript files. The proper way is to use the wp_enqueue_scripts hook. For instance, say you have javascript file you wish to load which requires jQuery to work, you enqueue the script and list jQuery as a dependency. WordPress does the rest:

<?php
function my_scripts_method() {
   // register your script location and dependencies
   wp_register_script('custom_script',
       get_template_directory_uri() . '/js/custom_script.js',
       array('jquery')
    );
   // enqueue the script
   wp_enqueue_script('custom_script');
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
?>

For styles (the same hook is used):

function my_styles_method() {  
    // Register the style like this for a theme:  
    wp_register_style( 'my-custom-style', get_template_directory_uri().'/css/custom-style.css');  

    // enqueue the stule  
    wp_enqueue_style( 'my-custom-style' );  
}  
add_action( 'wp_enqueue_scripts', 'my_styles_method' ); 

Please read this Codex pages on and wp_enqueue_script() and wp_enqueue_style()

It may not seem important, but particularly with loading scripts, you’ll probably find that loading them ‘manually’ will break your theme and/or plug-ins.

Leave a Comment