How do I make JavaScript file paths relative to the current file directory?

JavaScript file paths are relative to displayed page. How do I make JavaScript file paths relative to the current file directory?

For instance, I include a file sh/shThemeDefault.css into footer.php (there are under the same directory: wordpress/wp-content/themes/) by:

Read More
<script src="sh/shCore.js" type="text/javascript"></script>

While accessing a post (say http://example.com/post-A),

sh/shCore.js will be extended as http://example.com/post-A/sh/shCore.js, reporting not found error.

The right absolute path is http://example.com/wordpress/wp-content/themes/sh/shCore.js.


PS: I am installing SyntaxHighlighter by placing the following codes before /body in footer.php:

<link href="./sh/shCore.css" rel="stylesheet" type="text/css" />
<link href="./sh/shThemeDefault.css" rel="stylesheet" type="text/css" />

<script src="./sh/shCore.js" type="text/javascript"></script>
<script src="./sh/shAutoloader.js" type="text/javascript"></script>


<script type="text/javascript">
SyntaxHighlighter.autoloader(
    ['python', 'py', 'sh/shBrushPython.js'],
    ['java', 'sh/shBrushJava.js'],
    ['bash','shell','sh/shBrushBash.js'],
    ['css','sh/shBrushCss.js'],
    ['sql','sh/shBrushSql.js'],
    ['latex', 'tex','sh/shBrushLatex.js.js'],
    ['plain', 'text','sh/shBrushPlain.js'],
    ['php','sh/shBrushPhp.js'],
    ['js','jscript','javascript','sh/shBrushJScript.js'],
    ['xml', 'xhtml', 'xslt', 'html', 'xhtml','sh/shBrushXml.js']
);
SyntaxHighlighter.all();
</script>

Related posts

2 comments

  1. You shouldn’t be including CSS and JS files directly in your WordPress templates. Rather, you should be enqueueing them properly (in functions.php) via wp_enqueue_style():

    /**
     * Proper way to enqueue scripts and styles
     */
    function theme_name_scripts() {
        wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/shThemeDefault.css' );
        wp_enqueue_script( 'script-name', get_stylesheet_directory_uri() . '/js/example.js', array(), '1.0.0', true );
    }
    add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
    

    This will completely eliminate the issue you’re experiencing.

  2. In WordPress you can use the following code to get the template directory:
    <?php echo get_template_directory_uri(); ?>

    In your case will be something like:

    <link href="<?php echo get_template_directory_uri(); ?>/sh/shThemeDefault.css" rel="stylesheet" type="text/css" />
    

Comments are closed.