サポート » 使い方全般 » 個別記事とブログトップで、カスタムCSSを追加する。

  • 解決済 kes_2010

    (@kes_2010)


    現在以下のコードで、個別記事内にカスタムフィールドで入力したCSSを
    <head>内に表示させています。

    しかし、ブログトップ等で記事をそのまま複数件表示させているのですが、
    そこではカスタムCSSは表示できません。

    表示されている複数記事のIDを配列で取得できないものかと思ったのですが、
    よくわかりませんでした。

    ブログトップ等で、表示されている記事それぞれのカスタムフィールドの値を、
    取得できる方法は無いでしょうか?

    よろしくお願いいたします。

    function insert_custom_css() {
    	global $post;
    	if ( is_single() && ! is_attachment() ) {
    		$css = get_post_meta( $post->ID, 'css', true );
    		if ( $css ) {
    			$output = '<style type="text/css">'. "\n" ;
    			$output .= $css . "\n";
    			$output .= '</style>' . "\n";
    			echo $output;
    		}
    	}
    }
    add_action( 'wp_head', 'insert_custom_css' );
2件の返信を表示中 - 1 - 2件目 (全2件中)
  • モデレーター jim912

    (@jim912)

    kes_2010さん、こんにちは。

    通常は、$postsというグローバル変数に表示する記事のオブジェクトが格納されていますので、これをforeachなどでループしてカスタムフィールドの値を取得することができるかと思います。

    トピック投稿者 kes_2010

    (@kes_2010)

    jim912様

    早速のご返信、ありがとうございます。

    教えて頂いた「$posts」を使い、思っていたとおりに出来ました!

    「$posts」というグローバル変数があるとは知らなかったので、
    とても勉強になりました。

    今回は本当にありがとうございました。

    function insert_custom_css() {
    	global $post, $posts;
    
    	if( is_home() ) {
    		foreach( $posts as $post ) {
    			$array_css[] = get_post_meta( $post->ID, 'css', true );
    		}
    		$css = implode( "\n\n", array_filter( $array_css ) );
    	}
    	elseif ( is_single() && ! is_attachment() ) {
    		$css = get_post_meta( $post->ID, 'css', true );
    	}
    
    	if ( $css ) {
    		$output = '<style type="text/css">' . "\n";
    		$output .= $css . "\n";
    		$output .= '</style>' . "\n";
    		echo $output;
    	}
    }
    add_action( 'wp_head', 'insert_custom_css' );
2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「個別記事とブログトップで、カスタムCSSを追加する。」には新たに返信することはできません。