当前浏览:首页 / WordPress函数 / get_template_directory_uri()

get_template_directory_uri()

检索启用的主题的模板目录URI

directory

templatemore...

uri


返回

(string) 启用的主题模板目录的URI。


说明

注意

  • 检查SSL
  • 不返回地址结尾的斜杠


源码

查看源码 官方文档


更新日志

版本描述
1.5.0开始引入

使用示例

  • 示例1

    此函数用于返回根主题的URL。如果使用了子主题,并且希望将URL返回到当前子主题,请改用get_stylesheet_directory_uri()

  • 示例2

    使用get_template_directory_uri()引用静态图像路径的html:

    <img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" width="" height="" alt="" />
    
  • 示例3

    WordPress 4.7.0开始,您可以使用get_theme_file_uri(),此函数将为我们提供实际的子主题URL或主题URL(如果不存在子主题)。

  • 示例4

    使用 get_template_directory_uri() 加载js脚本文件

    add_action('wp_enqueue_scripts', 'wpdocs_scripts_method');
    
    /*
     * Enqueue a script with the correct path.
     */
    function wpdocs_scripts_method() {
    	wp_enqueue_script(
    		'custom_script',
    		get_template_directory_uri() . '/js/custom_script.js',
    		array('jquery')
    	);
    }
    
  • 示例5
    /**
     * 加载 scripts 和 styles.
     */
    function wpdocs_theme_slug_scripts() {
    	// Custom scripts require a unique slug (Theme Name).
    	wp_enqueue_script( 'theme-slug-custom-script', get_template_directory_uri() . '/js/custom-script.js', array(), '1.0.0', true );
    
    	/*
    	 * To avoid double loading Genericons will not need a slug. Same applies
    	 * to all other non-custom styles or scripts.
    	 */
    	wp_enqueue_style( 'genericons', get_template_directory_uri() . '/genericons/genericons.css', array(), '1.0.0' );
    }
    add_action( 'wp_enqueue_scripts', 'wpdocs_theme_slug_scripts' );