سؤال

what the best way to include images from the template's images folder? is it by using get_bloginfo('template_url')? I understood that its better to hard code the path to the images folder since this way you save function calls in PHP..

any thoughts?

هل كانت مفيدة؟

المحلول

The easiest and simplest way to do it is define a unique variable in your theme's functions.php file.

Such as:

<?php
$theme_name_images = get_bloginfo('stylesheet_directory') . '/images/';
?>

No need for classes as a previous answer suggested.

EDIT: It should be get_bloginfo, instead of bloginfo(), as Viper007Bond kindly pointed out.

نصائح أخرى

I understood that its better to hard code the path to the images folder since this way you save function calls in PHP..

I definitely wouldn't worry about function calls, WordPress' object cache will handle cache all that stuff for you. You could define the path as a constant if you wanted, but I generally wouldn't bother.

I would just do:

<img src="<?php bloginfo('stylesheet_directory')"?>/images/image.png" />

i edited this to

<img src="<?php bloginfo('stylesheet_directory');?>/images/image.png" /> (the above gives errors)

@Amit: It depends. Most function calls are pretty fast in PHP so if you are looking for performance I wouldn't worry about it too much. However I know how you feel seeing all those calls. Still, I'd never want to hardcode paths.

If you are going to be using get_bloginfo('template_url') many times in your theme why not assign it to a global variable in your functions.php file and then reference it everywhere you'd normally reference the function call? Make sure to name it something unlikely to conflict such as amits_template_url. So do this in functions.php:

global $amits_template_url;
$amits_template_url = get_bloginfo('template_url');

And then in your theme reference it everywhere you would have referenced get_bloginfo('template_url').

Well, it depends what kind of development you're doing. If you're doing plugin development, you need to use the functions because you'll never know for sure what the url structure will be. If you're doing specific work on a specific website, it's technically ok to hard code it, but that is still inadvisable, since it precludes the possibility that the url structure could ever change.

Whenever I develop plugins or themes, I structure the program in a class; that way, I can save repetitive values as properties of the object (e.g., WP URL and template_url). That way I can use them quickly without calling the functions repeatedly.

Just link your image files from your CSS file, that means you can use the relative path from the CSS file to the images. This is a CSS only solution. No PHP code needed. Work is done by the browser.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى wordpress.stackexchange
scroll top