Can’t use the variable from functions.php in header.php

I have this simple global variable for calling image path. I put it in functions.php so it can be used in any pages.

// Inside functions.php
$img = get_template_directory_uri().'/assets/img/';

// Inside header.php
<img src="<?php echo $img; ?>my-image.jpg">

But that variable returns empty when I call it inside header.php. Weirdly, it works fine when I call it in other template page like index.php.

Read More

I tried googling but the result always about the generic PHP header(Location).

Any solution for this?

Thanks

Related posts

Leave a Reply

2 comments

  1. Add this function to your functions.php:

    function img()
    {
        return get_template_directory_uri().'/assets/img/';
    }
    

    and use this in your header.php like this:

    <img src="<?php echo img(); ?>my-image.jpg">
    
  2. You can define it global (in header) before using it such as:

    <?php 
    // Inside functions.php
    $img = get_template_directory_uri().'/assets/img/';
    
    // Inside header.php
    global $img;
    ?>
    <img src="<?php echo $img; ?>my-image.jpg">
    

    It should work.

    Although @Ankit Agrawal’s solution is recommended.