Standing on the Shoulder of Linus

Home / 2013 / 1月 / 12 / Automatic CSS choice, based on WordPress Template Hierarchy

Automatic CSS choice, based on WordPress Template Hierarchy

These codes below automatically output css, based on Template Hierarchy.

When you are watching index.php, these codes output the index.css link, like < link rel=”stylesheet” href=”https://ounziw.com/wp-content/themes/THEMENAME/css/index.css” />. When you are watching, category.php, these codes output the category.css.

add_action('wp_head','page_template_css') ;
function page_template_css() {
global $template;
$dir = '/css'; // css directory. relative path from your theme.
$pos = strrpos($template, "/");
$template = substr($template, $pos);
$filename = str_replace('php', 'css', $template);
$fullfilename = get_stylesheet_directory() . $dir . $filename; 
    if (file_exists($fullfilename)) {
        print '<link rel="stylesheet" type="text/css" href="' . get_stylesheet_directory_uri() . $dir . $filename . '" />';
        print "n";
    }
}

You don’t have to use lots of if-clause, and still get different css files for different template php files. I hope these codes will help those who customize themes.

関連

Posted in WordPress | Tagged template
← 2012年を振り返って OpenStreetMap ワークショップ in 名古屋 #5 →

アーカイブ

人気の投稿とページ

  • キンドル本を印刷する(PDFに変換する)方法
  • 名古屋駅から国際センターまでの道のり(徒歩)
  • AGPL ライセンス(GPLとは似ているが違いもある)
  • 6年使ったイーモバイル(Y!mobile)を解約手続。店頭でSIM返却
  • JP-Secure SiteGuard WP Pluginは不正ログイン防止に役立つか

プロフィール

水野史土:月70万PVホームページ制作会社のレスキューワーク株式会社で、PHPソフトウェアのサポートを行っている。concrete5コミュニティリーダー、Novius OSコアコード貢献者でもある。 詳しくは管理者詳細参照。
大好評WordPress書籍「WordPressユーザーのためのPHP入門 はじめから、ていねいに。」サポートページ

Copyright © 2015 Standing on the Shoulder of Linus.