WordPress template directory php

get_template_directory_uri() │ WP 1.5.0

get_bloginfo(‘template_url’); — это алиас этой функции — при запросе этой опции будет вызвана эта фукнция.

  • Используйте get_stylesheet_directory_uri(), когда используется дочерняя тема и нужно получить её URL.
  • Используйте get_template_directory(), когда нужно получить путь до папки темы.
  • Используйте plugin_dir_url(), когда нужно получить URL для плагина.
Хуки из функции

Возвращает

Использование

get_template_directory_uri();

Примеры

#1 Использование функции в HTML теге

Для безопасности результат функции нужно очищать через esc_url() или esc_attr().

Впрочем такую очистку нужно делать абсолютно для всех функций которые используются в атрибутах тегов. Например, если такой очистки не будет, то ваш код не пройдет проверку при размещении темы/плагина в офф репозитории. Пример очистки:

#2 Получим путь до шаблона:

echo get_template_directory_uri(); // получим: http://example.com/wp-content/themes/theme_name

#3 Используем функцию, чтобы подключить скрипт:

add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); function my_scripts_method()< wp_enqueue_script( 'custom_script', get_template_directory_uri() . '/js/custom_script.js', ['jquery'] ); >

Список изменений

Код get_template_directory_uri() get template directory uri WP 6.2.2

function get_template_directory_uri() < $template = str_replace( '%2F', '/', rawurlencode( get_template() ) ); $theme_root_uri = get_theme_root_uri( $template ); $template_dir_uri = "$theme_root_uri/$template"; /** * Filters the active theme directory URI. * * @since 1.5.0 * * @param string $template_dir_uri The URI of the active theme directory. * @param string $template Directory name of the active theme. * @param string $theme_root_uri The themes root URI. */ return apply_filters( 'template_directory_uri', $template_dir_uri, $template, $theme_root_uri ); >

Cвязанные функции

theme path url (папка темы)

Подключение файлов темы

Доброе время суток! Подскажите, какой подход в плане скорости работы лучше? Сохранять эту функцию в переменную

$templatePath = esc_url( get_template_directory_uri() )
style comment-meta / comm_meta_js"> 
0
9 месяцев назад #
Wordpress template directory php
Kama9400

Логичнее:

$templatePath = esc_url( get_template_directory_uri() );

Источник

get_template_directory_uri() │ WP 1.5.0

Retrieve current theme directory URI. Returns the URL to the root theme, not a child one. Doesn't contain a closing slash at the end. You can also use get_bloginfo('template_url'); instead of this function.

Hooks from the function

Return

Usage

get_template_directory_uri();

Examples

#1 Get the URL to the theme

echo get_template_directory_uri(); // output: http://example.com/wp-content/themes/theme_name

#2 Including a script

add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); function my_scripts_method() < wp_enqueue_script( 'custom_script', get_template_directory_uri() . '/js/custom_script.js', ['jquery'] ); >

#3 Using a function in an HTML tag

To be safe, the result of the function should be cleared with esc_url() or esc_attr(). This cleanup should be done for all functions which are used in tag attributes. For example, if this cleanup is not done, your code will not pass the check when placing the theme/plugin in the official repository. An example of cleaning:

Changelog

get_template_directory_uri() get template directory uri code WP 6.2.2

function get_template_directory_uri() < $template = str_replace( '%2F', '/', rawurlencode( get_template() ) ); $theme_root_uri = get_theme_root_uri( $template ); $template_dir_uri = "$theme_root_uri/$template"; /** * Filters the active theme directory URI. * * @since 1.5.0 * * @param string $template_dir_uri The URI of the active theme directory. * @param string $template Directory name of the active theme. * @param string $theme_root_uri The themes root URI. */ return apply_filters( 'template_directory_uri', $template_dir_uri, $template, $theme_root_uri ); >

theme path (theme folder url)

Theme files connection

Источник

How do I get the theme URL in PHP?

I need to get the URL of my theme directory to reference an image in the theme's image/headers directory. How is this done in PHP?

4 Answers 4

This function will return the theme directory URL so you can use it in other functions:

get_bloginfo('template_directory'); 

Alternatively, this function will echo the theme directory URL to the browser:

bloginfo('template_directory'); 

So an example for an image in the themes images/headers folder would be:

NOTE: this will give you the path to the parent theme if you are currently using a child theme, and not the active child theme. A longer answer below explains this in more detail.

What @EAMann said, with a caveat. Eric is right about the general approach and how the functions bloginfo() and get_bloginfo() work and about how to pass the parameter 'template_directory' to get the value you need for (most) themes.

However there is a caveat and that caveat is with the newer Child Themes. If you are using a child theme then 'template_directory' is probably not what you want unless you are actually trying to refer to an image that is in the parent theme directory. Instead for child themes what you probably want is to pass stylesheet_directory (I know, I know, the names don't tell you what they are but hey, that's just the way it is!) Borrowing somewhat from Eric's reply using stylesheet_directory would look like this (I shortened the example so it would not wrap):

To illustrate the point I wrote a quick standalone file you can drop in your website's root as test.php and run to see what it outputs. First run with a regular theme like TwentyTen then run with a child theme:

'; foreach($bloginfo_params as $param) < $info = get_bloginfo($param); echo ": "; > echo ''; 

If you notice things you might notice that there's a lot more to what you can pass to bloginfo() and get_bloginfo() ; study the code and the screenshot below for ideas.

Looking at the screenshot you can see that stylesheet_directory returns the same thing as 'template_directory' for a regular theme but a different value, and probably the value you need for a child theme.

For clarity on this screenshot, wp30.dev is a domain that runs only on my local computer. It is currently an instance of WordPress 3.0.1 and it is configured at 127.0.0.1 (same as localhost ) on my laptop and I use it for testing ad-hoc examples like this. I used VirtualHostX as a convenience on the Mac OS X to help me set up those private non-routable .dev domains but anyone can do it manually by editing the computer's hosts file and the ? httpd.conf file.

By the way, in case you are not familiar with Child Themes where are two other WordPress Answers that might help:

Источник

Читайте также:  Open sqlite3 file php
Оцените статью