If you haven’t read the recent posts I am taking a bit of time off to work on personal projects and explore new opportunities. Most of the projects I am focusing on revolve around WordPress a platform I’ve been working with for quite a few years. While doing this I decided to get back to writing about it as well so to start I am going to start looking back at some of the useful things I’ve done with Custom Fields. If you are unfamiliar have a look at Custom Fields – WordPress Codex.
Single Post Custom CSS
To start you I got into my functions.php and created a function to grab the custom css for the post. There are of course other ways of doing this but I prefer to set up a function and later call it in my header.php. So:
function my_custom_css() {
global $post;
$css_key = get_post_meta($post->ID, 'css', true);
if (!empty($css_key) && is_single()) {
echo '<link rel="stylesheet" href="' . get_bloginfo('template_directory') . '/css/post/' . get_post_meta($post->ID, 'css', true) . '" type="text/css" media="screen" />';
}
}
The first thing we are doing here is setting up the variable $css_key. On the next line we are looking to see if the custom field key is present on the post page, basically what this is saying is if the custom field ‘css’ is available then do this. Notice the is_single() is present here as well since we are looking to target single post pages only. What it does is then echo the appropriate stylesheet.
You will notice that I set up the full path to my stylesheet. Since I will be putting all of my custom stylesheets in one place ../css/post/ it makes no sense to have to type out the full path every time I add a stylesheet to a post. So now when I go to add my custom field all I have to do is enter the key ‘css’ followed by the value of ‘example-post-1.css’.
Now when we finally call this to the header it will look something like this:
<link rel="stylesheet" href="http://mysite.com/wp-content/themes/mytheme/css/post/example-post-1.css" type="text/css" media="screen" />Adding it to the header.php file. Now we want to actually add this to the header so that it works, so open up your header.php and look for a line something like this:
<link rel="stylesheet" href="http://mysite.com/wp-content/themes/mytheme/style.css" type="text/css" media="screen" />After that you want to add you new function:
<?php my_custom_css(); ?>This is a basic concept that can be used in a variety of creative ways, I would tell you what I am doing with it right now but unfortunately that is top secret.
I should note here that there are other ways of calling this to your header.php such as using hooks like wp_head. (I have a preference to using a hook considering most of my work is done via Child Theme).