Quantcast
Channel: Suzanne Ahjira» Tutorials
Viewing all articles
Browse latest Browse all 29

Insert Styles Into wp_head Hook Using Custom Style Hook

$
0
0

Well that title didn’t really make things clear. It’s true, this one is a bit funky. I’m working on a new theme and in more than one part of functions.php, I’m inserting custom styles into the wp_head hook with an HTML style tag. I don’t like a cluttered <head> area so I got thinking about how I can just add my styles into one declaration using a hook. Hum..

Here’s what I devised:

// STYLE DECLARATION WITH HOOK ------------------------------- //

add_action( 'wp_head', 'ahjira_insert_style_overrides' );
function ahjira_insert_style_overrides() {

  echo '<style type="text/css">' . "\n";
  do_action( 'ahjira_insert_styles' );
  echo '</style>' . "\n";

}

Now that’s a simple little solution. If you look carefully, you’ll see I create my own hook, ahjira_insert_styles exactly where I want my styles to appear. Now I have a way, from any other function in functions.php, to insert styles into that one declaration.

Here’s an example of how I do that…

add_action( 'ahjira_insert_styles', 'insert_bgimg' );
function insert_bgimg() {
  global $post;

  if(get_post_meta($post->ID, '_cmb_background-color', TRUE)) {
    $bgcolor = 'background-color: ' . get_post_meta($post->ID, '_cmb_background-color', TRUE) . ');';
  }
  if(get_post_meta($post->ID, '_cmb_background-image', TRUE)) {
    $bgimg = 'background-image:url(' . get_post_meta($post->ID, '_cmb_background-image', TRUE) . ');';
  }

  if( $bgcolor || $bgimg ) {
    $styles = 'body { ' . $bgcolor . $bgimg . ' }';
  }

  echo $styles;

}

In that example, I’m checking to see if an image URL or color was specified as post-meta on a post and if so, I create the CSS styles for each one. Then I apply them to the final $styles variable and echo that. That allowed me to insert styles from multiple functions without creating duplicate style tags. Nice.


Viewing all articles
Browse latest Browse all 29

Trending Articles