Can't use the variable from functions.php in h

2019-06-06 07:17发布

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.

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

Any solution for this?

Thanks

标签: wordpress
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-06 07:32

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.

查看更多
不美不萌又怎样
3楼-- · 2019-06-06 07:35

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">
查看更多
登录 后发表回答