wp_enqueue_style and rel other than stylesheet?

2019-04-22 03:06发布

I create (or better try) to create my first WordPress theme with Less.

What I do is to use a script like that into my functions.php

wp_register_style('screen_css', get_bloginfo('template_url') . '/css/screen.less', array(), false, 'screen');
wp_enqueue_style('screen_css');

and the result is that:

<link rel='stylesheet' id='stigma_screen-css'  href='http://www.stigmahost.dch/wp-content/themes/stigmahost/css/screen.less?ver=1.0' type='text/css' media='screen' />

The question is, can I change somehow the rel="stylesheet" when I using the wp_register_style() function ?

2条回答
\"骚年 ilove
2楼-- · 2019-04-22 03:08

While neither function will let you pass that value in, you do have access to the tag before it is rendered with the style_loader_tag filter. If you do something like this...

add_filter('style_loader_tag', 'my_style_loader_tag_function');

function my_style_loader_tag_function($tag){
  //do stuff here to find and replace the rel attribute

  return $tag;
}

...you should be able to replace the rel attribute with whatever you want. Keep in mind that this filter will pass in the whole tag as html, so you'll have to do a preg_replace() or something similar to replace the value with what you want. Also, this filter will run every time you enqueue a stylesheet, so make sure you test that you've got the right one (with a preg_match() or something) before you alter the rel attribute.

查看更多
等我变得足够好
3楼-- · 2019-04-22 03:20

i know this is an old q, but it helped me figure this out. borrowing from brandwaffle's answer here's the full function I used:

function childtheme_scripts() {

wp_enqueue_style('less',get_stylesheet_directory_uri() .'/style.less');
add_filter('style_loader_tag', 'my_style_loader_tag_function');

wp_enqueue_script('less',get_stylesheet_directory_uri() .'/jscripts/less-1.3.0.min.js', false,'1.3.0');

}
add_action('wp_enqueue_scripts','childtheme_scripts', 1);


function my_style_loader_tag_function($tag){
  //do stuff here to find and replace the rel attribute    
  return preg_replace("/='stylesheet' id='less-css'/", "='stylesheet/less' id='less-css'", $tag);
}
查看更多
登录 后发表回答