ワードプレス
カスタムフィールドの入力値や投稿IDなどをCSSに出力
★テーマフォルダにcustom-style.cssで書きだす場合
※custom-style.cssを設置する必要はありません。
※投稿更新時にcustom-style.cssも自動更新されます。
※CSSを書きだすPHPは、テーマフォルダのincフォルダ内にcustom-style.phpに書く場合
↓↓↓
★function.php
//カスタムフィールドCSS設定 function generate_options_css() { $ss_dir = get_stylesheet_directory(); ob_start(); require($ss_dir . '/inc/custom-style.php'); $css = ob_get_clean(); file_put_contents($ss_dir . '/custom-style.css', $css, LOCK_EX); } add_action( 'acf/save_post', 'generate_options_css', 20 ); function theme_enqueue_styles() { wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri() . '/custom-style.css' ); } add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
★CSSを設定するPHP
カスタムフィールド値でもIDでも、条件(カテゴリーに投稿があった場合など)のループでもOKです。
/inc/custom-style.php
/* 特定カテゴリーに投稿IDの値をclass名にして 背景画像(カスタムフィールドで登録)にしたい場合 今回はクラス名を「bg投稿ID」としました*/ <?php query_posts( 'category_name=カテゴリースラッグ'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> .bg<?php the_ID(); ?> { background: url(<?php the_field("フィールド名", $post->ID); ?>) no-repeat center center; } <?php endwhile; ?> <?php endif; wp_reset_query(); ?>
★ヘッダーにCSSを読み込む
<link href="<?php echo get_template_directory_uri() ?>/custom-style.css" rel="stylesheet" media="all">
★テンプレート
<?php query_posts( 'category_name=カテゴリースラッグ'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <div class="repeatCell"> <a href="<?php the_permalink(); ?>"> <div class="bg<?php the_ID(); ?>"> コンテンツなど </div> </a> </div> <!--/repeatCell--> <?php endwhile; ?> <?php endif; wp_reset_query(); ?>