web-dev-qa-db-ja.com

Wp_register_styleを通じて生成されたリンクタグに属性を追加しますか?

私の最初の質問はここで答えられました: Google Fonts given:要求されたリソースに 'Access-Control-Allow-Origin'ヘッダが存在しません。

Googleフォントリンクタグにdata-noprefix属性を追加する方法はありますか。

私のfunctions.phpはこのようになります:

wp_register_script( 'prefixfree', get_template_directory_uri().'/js/prefixfree.min.js', array( 'jquery' ) );
wp_enqueue_script( 'prefixfree' );

wp_register_style( 'google-fonts', 'http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,600,600italic,700,700italic', '', '', 'all' );
wp_enqueue_style( 'google-fonts' );

Birgireの助けを借りて答えなさい:

add_filter( 'style_loader_tag', 'add_noprefix_attribute', 10, 2 );

function add_noprefix_attribute($link, $handle) {
    if( $handle === 'google-fonts' ) {
        $link = str_replace( '/>', 'data-noprefix />', $link );
    }
    return $link;
}
3
user8737780

WP_Style クラスを見ると、 style_loader_tag フィルタが便利です。

例えば試してみてください。

add_filter( 'style_loader_tag', function( $link, $handle )
{
    if( 'google-fonts' === $handle )
    {
        $link = str_replace( '/>', ' data-noprefix />', $link );
    }
    return $link;
}, 10, 2 );
4
birgire