Forums

Getting custom fields on blog page (for internal styles in doc head) (2 posts)

  1. eyewinder
    Member
    Posted 7 months ago #

    I'm working on a parent theme (based on the Hybrid Core framework) and am having some trouble collecting custom field values for all listed posts on the blog home page.

    I've been using a custom field "css" on pages and posts to embed article-specific styles into the document head. This has been working perfectly on singular pages, however, on the blog home page, only styles from the first post are embedded. If the first post does not have the "css" custom field, no styles are embedded for any of the following posts.

    I'm not particularly experienced with PHP, but I assume that the value for each listed post needs to be stored in an array and then output sequentially as styles in my document head. Here is the code I'm currently using in my functions.php:

    function footprint_custom_css() {
    	global $post;
    
    	if ( !is_search() && !is_404() && get_post_meta( $post->ID, 'css', true ) ) { // search and 404 pages excluded to avoid errors
    
    		$css_key = get_post_meta( $post->ID, 'css', true );
    
    		if ( !empty( $css_key ) ) {
    			echo '<style type="text/css" media="screen, projection, print">' . "\n" . $css_key . "\n" . '</style>' . "\n";
    		}
    	}
    }
    add_action( 'wp_head', 'footprint_custom_css', 8 );

    Is there a simple way to get and store all values of a certain custom field from within the loop?

    Note: I tested embedding the styles directly into each listed post (using "echo get_post_meta( $post->ID, 'css', true )" in the loop). While this functionally works, it doesn't result in valid code… :(

  2. eyewinder
    Member
    Posted 7 months ago #

    Update:
    After a bunch of experimentation and reading about the loop (outside of template files), I think I have a workable solution. Below is the latest version of the function. Any suggestions to improve/simplify the code are more than welcome...

    // Get styles from custom field 'css' in blog loop and embed into document head
    function footprint_blog_custom_css() {
    	global $post;
    
    	if ( is_home() ) {
    		$custom_css_array = array();
    
    		while ( have_posts() ) : the_post();
    			$blog_post_css = get_post_meta( $post->ID, 'css', true );
    			if ( !empty( $blog_post_css ) ) {
    				$custom_css_array[] = $blog_post_css;
    			}
    		endwhile;
    
    		$blog_custom_css = implode( "\n", $custom_css_array );
    
    		if ( !empty( $blog_custom_css ) ) {
    			echo '<style type="text/css" media="screen, projection">' . "\n" . $blog_custom_css . "\n" . '</style>' . "\n";
    		}
    	}
    }

Reply

You must log in to post.

About this Topic