Archive for the ‘Tutorials’ category
How I Made an Annual Color Algorithm
The foundation of my Kaleidoscope theme and Mini Quilt plugin is the color algorithm. For those who don’t know, the Kaleidoscope theme for WordPress is a simple theme I made (almost three years ago) that changes the colors of its pages based on when posts were written. (It’s the theme currently being used here.) It features quilts, which show recent posts in blocks of color. The small multicolored quilt in the sidebar of the theme is available separately, and can be added to any theme as a sidebar widget with the Mini Quilt plugin.
Both the theme and plugin are rather primitive by today’s WordPress standards because they’ve seen no changes in two and half years. But their current outdatedness is irrelevant to value of the underlying color algorithm. This article exists because someday someone may have the same idea I did and find this guide of what I did — both programmatically and philosophically — helpful. They may even find it useful to just lift my code — which is all GPL licensed — and use it as is. I’m not entirely satisfied that the methods I used here are the best possible ones, but I feel certain that anyone interested in the idea will benefit from knowing them.
The Mother Function
Let’s start with the primary function that either my theme or plugin calls. (Technically the currently available versions, call a similarly named but different function. As I’ve been working on getting better at web stuff, I decided to recode that version. If and when I update the theme or plugin, they’ll have this algorithm.)
function date_to_color( $day, $year ) {
$red = color_maker( $day, $year, 20, 134 ); //18, 134
$green = color_maker( $day, $year, 20, 240 ); //20, 240
$blue = color_maker( $day, $year, 10, 0 ); // 10, 0
return $rgb = "{$red}{$green}{$blue}"; //concanate the calculated colors and return them
}
Essentially, this is the function that is called anywhere — in WordPress the call looks like date_to_color(get_the_time('z'), get_the_time('Y')) — the color for a day is needed. You’ll notice that all this does is call the color_maker function three times and then return the concatenated (joined) six digit hexadecimal number to wherever it was called. The one thing I’d call your attention to is that it’s passing along four values to that function — the day and year that are submitted when this function is called, and two values that you’ll see later I call $broaden and $shift.
(If you’re wondering, it is considered good form to name functions you write with a prefix like kal_function_name. This prevents pollution of the global name space. For the purposes of this tutorial, I’ve left off the prefixes.)
The Color Determining Equation
Here we’ll begin the important function, color_maker. I’ve broken it into three separate sections that reflect the conceptual underpinnings of the function. Not coincidentally, when I first made this algorithm (the version that’s currently in the theme & plugin) these three parts were three separate functions. It was only upon looking at what I’d done at some distance that I saw that that was needless complexity. Anyway, here’s the first conceptual unit.
function color_maker( $day, $year, $broaden=0, $shift=0 ) {
$in_degree = .986*$day; // from 365.25=>360
/* pshift =
New degree value = incoming period shift + degree from year - sine function
Sine Function = Random value * sine of shifted value
> This essentially works to make the coming cosine function stay near its peak for a while
> based on the magnitude of the random value
*/
$pshift = $shift+$in_degree-($broaden*sin((M_PI*($in_degree+$shift))/180));
The first line here — one of two that isn’t actually a comment — does a pretty simple thing. It converts from days of the year (of which there are 365.25), and makes that into 360 degrees in a circle. This is utterly straightforward.
The next part is a bit more complicated. Essentially, what we’re doing is getting a value ($pshift) ready for the next step, a cosine function that really determines the color, by shifting our period values into more appropriate inputs to the next function. For example, January 23 needs different values for red, green, and blue in order to give the color I want. I do that here by shifting each color by the value passed on ($shift) from the first function. My shift values are 134 for red, 240 for green, and 0 for blue. This means that for January 23 we’ll pass along values of about 150, 260, and 20. If you know trigonometry well, you’re beginning to get a sense of what colors we’ll make.
There’s another component here though, which is that $broaden value I mentioned earlier. The need for broadening was something I realized as I started to see the colors the cosine wave function generated. They were frequently washed out and drab. I realized that if I was able to make the function’s peaks broader I’d have more color saturation which would correct that problem. That’s what that $broaden variable and sine function are doing. They’re creating values — with the yin and yang relationship of sine and cosine — that will favor the peaks of cosine and shrink the valleys. I don’t want to get too much into the math here (though if you’re interested I’d be happy to explain further), but just know that the larger the value I passed to $broaden in the first function, the stronger the peak-favoring effect is.
Determining what values to use for $broaden and $shift for red, green, and blue is more an art than a science. It’s where I drew on what aesthetic power I had (and the color accuracy of an uncalibrated old LCD) and where there could be the most room for improvement. To figure out what values to use, I created a page with boxes for each day of the year and fiddled until I felt the basic proportions of red, green, and blue were about right for a given season and day. Had I been using a different monitor in different lighting conditions, I may have settled on different (better) values.
The Darkness Determining Equations
Having gotten a single degree value ($pshift) for each color for a day, we need to make that into a color. That’s what this section does:
$year_diff = date('Y')-$year;
$hshift = .08*$year_diff; // to be used for further away years fading
if ( $hshift > 1 ) { //this assures that the colors are always valid otherwise we could get negative numbers
$hshift = 1;
}
$HBASE = .82; //the center of the function; set between 0 and 2, lower are more saturated (darker)
if ( $HBASE > 1 ) {
$HSAFE = 2-$HBASE; // $hsafe is to ensure no final values greater than 2, which would create invalid colors
} else {
$HSAFE = $HBASE;
}
/* calced_color ==
Use Cosine to create a weighted set of results between 0 and 2
Multiply by 127.5 to get results between 0 and 255
dechex for results between 0 and FF
+Change the first (and only the first) +/- to toggle fade/darken
*/
$calced_color = dechex(127.5*(($HBASE-($HSAFE*$hshift))+(($HSAFE-($HSAFE*$hshift))*(cos((M_PI*($pshift))/180)))));
It’s important to realize that much of this is preamble. The last line — the one that begins “$calcedColor = ...“ — is the important one. Everything else is just tuning up before the show.
The first part of this related to the year. In addition to deriving a different color for each day, my color function also determines brightness based on age. Two posts from July 5, one from today and one from four years ago, will be noticeably different shades. This means that a quick glance at a color derived from the date can tell not only that a post is from Julyish, but Julyish a few years ago.
To do this we essentially figure out how much the submitted year — passed on from the preliminary function — differs from the current year, and then make an $hshift value for it. Because a post could conceivably be more than 12 years old — which is when they become uniformly black — any value over one that might arise is just adjusted down to uniformly black.
The next block of stuff are a number of constants that I keep around only for the sake of future tuning of the function. $HBASE is essentially what will be the center point of our cosine function, and $HSAFE just assures that no value of $HBASE will break the cosine function. They’re not really doing much here, but if I or anyone else feel like tweaking the function, I’d rather it be easy and obvious to edit than hard. (If you are interested in tweaking, higher values of $HBASE give lighter colors. Setting it to 1.3 gives pastel colors, setting it to .6 gives significantly darker hues.)
Finally we’re to that important final line, which does about twelve different things. The important ones, starting from the right and working left are: uses multiplication with some $h values and cosine to get a basic value for a given color, and them shifts that around by adding and subtracting more $H values to get a value between 0 and 2. Then it multiplies by 127.5 to get a value between 0 and 255, the limit of two-digit hexadecimal numbers, and converts that number into hexadecimal, yielding a final range between 0 and FF. (Again, vagueness on the math is intentional, because otherwise this thing would be even longer than its current too-long length. I’m happy to provide more detail if desired.)
The Kludge
This final bit is a kludge that I couldn’t find a way around (even while I think there must be one.)
if ( strlen( $calced_color ) < 2 ) { //single digit calced_color values give invalid colors
$calced_color = "0".$calced_color; // so add a zero if it's a single digit
}
return $calced_color;
}
Essentially, after each color’s (red, green, and blue) value was determined between 0 and FF, I had a problem. If the red value was 253 in decimal, that converted to the two digit hexadecimal number FD. That was all well and good, but if the value of red had instead been 3 in decimal I would get 3 in hexadecimal. Because a five-digit color value like 3FDFD isn’t valid, I need to ensure that I instead get 03FDFD, which was assured by this function. Its essential logic is: “Is this number shorter than two digits? If yes, put a zero on the front.” Thus FD stays FD, but 3 becomes 03, and D become 0D.
After that kludge, the function returns its two digit hex number to the primary function, where it’s melded with the two others it derived to give a single six-digit value back to the theme or plugin that asked for a color. Thus given values like 188 (today’s day of the year) and 2011 (this year), it derives this sort of brownish yellow that you’re reading this post on. I think it conveys pretty well the dried out heat that I think of in July. It does this by iterating three time (once each for red, green, and blue) through a function with three steps. Those steps are essentially (1) shift to account for the amount of a given color that’s appropriate for the time of year (2) figure out the two digit hexadecimal value to get the right quantity for that color and (3) ensure success in making a six digit hexadecimal color.
I’ve not cured cancer for you, I know. But I hope I’ve given a new way to look at colors, and some valuable knowledge about one way to play with them. Before I close, it seems appropriate to note that I was turned on to this idea by Shaun Inman, though the implementation is all mine. I’m hoping that if my discussion has gotten you interested in this game, you now have some idea how to start.
Using Images in your Blog Posts
I — and many other people who sometimes opine on blog design issues — think its rather useful to have images on posts. They’re a quick introduction to your topic, a way to jazz up your text, and a great way stand out at least a little bit.
And if you’re like me, you’re not exactly a prolific photographer with thousands of images that you can use for all kinds of topic you might write about. Also, you probably don’t want to go about buying photos to use. In such a case you have two choices, one legal and one not. (I’m actually ignoring the existence of free stock photos, because I’ve never found them terribly useful.)
The illegal — or at least problematic — way is to take them from other website. One thing I used to do, was hotlink directly to Yahoo!’s images. And I’ve also used Google Image Search, without regard for who owned the image or what have you. If it looks roughly like I wanted I’d upload it to my own server and use it.
And so now, assuming we’re not pirates, we have a problem in need of a solution. And there is a very easy solution: Creative Commons images. As you very well may know, Creative Commons is a license in which the creator give away some — but crucially not all — rights to what they’ve produced.
The easiest and best ways to find Creative Commons licensed images is with a Flickr Advanced Search. Down on the bottom of that page, you’ll find an option for Creative Commons licensed images. For myself, I always choose “Find content to use commercially” simply because I want the least stringent and problematic license. What you find there doesn’t exactly leave you home free. Almost all — perhaps all, I don’t know — CC images require a citation. Some also require other things, but this is the most important requirement from a design perspective.
Designing Images with Citations
We’ve established the need for citations on images you might use on your blog. And there are indeed a number of ways to cite. Many conscientious people lacking some know-how simply add a “The image on this post is from Mr. Flickr” at the end their posts. But for myself, I wanted something at least a bit more elegant than that.
For inspiration, I’d always liked the way that The Economist’s website displays the citations on its images (see random example), and decided to mirror it. There were mild changes I made beyond that — for my own aesthetic preferences, but that was the layout — and CSS code — to which I referred while devising this solution — which you may notice in the out-of-place-photos of Optimus Prime and Canadian geese, each lazily stolen from Frozen Toothpaste entries (here and here).
I have two basic ways, both of which work essentially like this in WordPress’s “code” editor for a given post:
<p class="rightcite">
<span><a href="http://www.dummyurl.com/">Dummy Photographer</a></span>
<img src="http://www.myadress.com/images/dummy.jpg" />
</p>
As you may be able to tell from this rather simple (X)HTML, this simple creates a paragraph while will carry the styling from the CSS class “rightcite” — more on what that means later. The next line is the photographers name, with a link to the URL that they want used for citation. For our purposes, it doesn’t really matter what’s on that line so long as it’s wrapped with the “span” tag, again used for styling. The third line is simply the image, preferably hosted on your servers, though there’s no reason it must be.
A note: The use of the paragraph (“p”) division rather than the more traditional “div” simply because WordPress seems to choke on anything but the paragraph division. If you’re using a different content management system, feel free to see if it can handle the use of a “div” rather than a “p.”
Now, we must style this stuff so that it looks good on our site:
p.rightcite {
display: block;
float: right;
margin: .1em 0 .1em .5em;
background: #f1f1f1;
padding: .2em;
border: 1px solid black;
}
p.rightcite span {
display: block;
text-align: right;
font-size: .8em;
color: #555;
margin: -.5em 0 -.4em 0;
}
As you may be able to tell, the first set of styles is for every part of the “rightcite” paragraph. The crucial things to note are the “display” and “float” properties. The rest just makes it look the way I want, but those two make the paragraph float to the right.
The second set of styles is for our citation, again the most important part here is the “display” attribute, which prevents the citation from floating all over the map. The rest is again mostly for aesthetic concerns.
Now, you may be interested to see a similar thing for a centered image, which is just a bit more complicated.
p.centercite {
display: block;
text-align: center;
margin: .8em auto;
width: 468px;
}
The crucial thing here is the width declaration, which is needed to keep our “span” text from floating away. Obviously, by declaring a width for this paragraph you’ll have to keep your images to that width for proper functioning. You can change that width in an implementation on your own blog, but I wouldn’t recommend changing it once you’ve decided what width you’ll use.
There are some other notable ways to do a similar thing as all this with different methods. The most interesting and prominent in my mind is Derek Punsalan’s, which uses custom fields. I’ll leave the explanation of that technique to him.
Making the Frozen Toothpaste Archives
Last week, I finally switched my blog, Frozen Toothpaste, to a theme of my own creation. It’s unoriginally called “FTp_one,” after BWO_one on which it’s based. And though FTp_one will probably never be freely-available, I’m going to do my best to make any interesting aspects of it — sadly there aren’t many — common knowledge.
One of the best features in FTp_one is the Archives. I talked about how to improve archives from the WordPress norm previously, and what I’m about to explain builds on that. You may also want to find out how to show your archives page in WordPress, if you’re not certain of that process.
How it’s better
The Frozen Toothpaste archive began with the same archives.php file that is included in my themes (that’s the one with Justin Blanton’s Smart Archives plugin built in). I added three aspects, however, all of which are significant improvements on that version. Because they’re still far from the norm in WordPress themes, I’ve decided I don’t want to natively include them in my themes, but I do want to make them easy to implement. That’s why you’ll find a link at the bottom of this article to the full archives.php I’m using at Frozen Toothpaste. This should easily drop into place in ANY WordPress theme and installation, though it may look a little wonky without the necessary styles.
Okay, lets discuss the three big improvements. The first is that there are words on the Archives page. This shouldn’t be half as novel as it is. It’s also notable that in those words are links to each section of what can be a very long archives page.
Secondly, there is a recommendations section. This is a very useful feature because, well, no one’s likely to read everything you’ve ever written to find the best stuff. The recommendations sections is great way for visitors to see some your best stuff and easily find out if they like what you’re doing.
The final feature is the tag cloud. Since WordPress 2.3 was released, making a tag cloud has been easy. The issue is that for established blogs with lots of back content, getting all of that tagged is problematic. Also, because many people are still running WP2.2 and earlier, I’ve decided to leave any tag data out of my canonical theme work.
How I did it
Now to the implementation. Both the “text” and recommendations section are enabled by the same basic features that all other archives.php seem to lack (for reasons I don’t understand). Essentially, most archive pages omit The Loop, which tells WordPess to get the words entered into the “Post” section for your archives page (as it does for every other page.) To correct this problem takes only a few simple lines:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="archivetext">
<?php the_content(); ?>
</div>
<?php endwhile; endif; ?>
These lines are essentially the basic loop that makes WordPress run. The first line tells WordPress to proceed if there’s text to display, the third line spits out the text, and the fifth tells the processor to proceed if there was nothing to display. (Lines two and four are merely to make it easy to style the text that WordPress has spit out.)
With this code included in your archives.php file, any text you enter into WordPress (as you normally would) will be displayed. This allows you to easily create and edit your recommendations section, because it’s as easy to get to as a normal page in WordPress. This also allows you to create links your category section, for example, by simply including a link to “#category.”
Finally, the tag cloud. As I said, this is scandalously easy to do in 2.3 and above. All you need are these two lines:
<h3><a name="tags"></a>By tags:</h3>
<?php wp_tag_cloud('smallest=10&largest=28&number=30'); ?>
Here the first line merely gives us a title for the section, including the syntax so you can link to the section with a simple “#tags” link. The second line leverages WordPress’s wp_tag_cloud command to create the cloud. It also includes instructions that the smallest output should be 10 pixels tall, the largest should be 28, and that we only want it to show the 30 most common tags. All of those values can be changed to anything you want. (There are also other variables for this command, which you can find in the WordPress Codex.)
Give it to me
There it is: all the instructions you need to improve any archives.php page. And now, the whole page, as promised, for you to drop into any theme you think could benefit from a better archive. Download it! (The file you’re downloading is archives.phps, you’ll want to rename it archives.php before you try to use it.) Happy blogging!
A Better WordPress Monthly Archives
If there’s one big problem with WordPress (and blogs in general) it’s that posts come and go very quickly. This is great for people who are embarrassed by what they’re writing, but for the average person this can be a great disappointment.
It also doesn’t help the case that WordPress’s default Archives page is ugly and hard to use. Nor that most free themes that contain an Archives page aren’t much better.
Since you may be a little confused, dear reader, some visuals. The default WordPress archives page (that’s archives.php for those keeping score at home) is pictured at right (click for bigger).
Anyone who’s ever used it will know that they’re taken from the monthly link to pages that simply show all entries from that month in full form (this time we’re talking about archive.php sportsfans). The format and contents of those pages doesn’t concern us now, as it’s a long-standing — even if unwise — tradition that clicking “February 2007” on the blog of anyone mildly prolific is a dangerous idea.
If you look very hard at improving the Archives page in WordPress, you’ll quickly come to understand why they tend to be so sub-par. WordPress’s native function to create archives (wp_get_archives) is frighteningly limited in it’s abilities. I’ll spare you the details, but suffice it to say that nothing it outputs is much better than what we’ve seen.
Since WordPress itself fails, a different application is needed. Having already found Justin Blanton’s Smart Archives plugin — which I used to make my archives at Frozen Toothpaste more presentable — I decided that was a good place to start.
As the Frozen Toothpaste archive shows (see left), the Smart Archive plugin allows you to cleanly display all the your writings from a given month listed chronologically. This, I decided, was the Archives page I wanted my themes to have.
But requiring plugins for a theme to work is fraught with problems. It requires more work than the average WordPress user can or wants to commit to. So however I made my archive, it had to be inside the theme. The easiest way to do that: include the plugin on the page that creates the archives — archives.php.
Though I’m neither a PHP or server-load “pro,” I couldn’t find much of a downside to to putting the code from the plug-in on the page (if you are such a person and can tell me that there is a problem, please do). And, better still, doing so would make the creation of a nice monthly archive as easy as the creation of a default poor one.
So essentially, that’s what I did. I did do a great deal of shrinking and modifying of Mr. Blanton’s plugin, but it meat of it is still intact. Most of my cuts were becuase I required it to do far less than the plugin can. I wanted the code as lean as it could be while still providing the necessary function, which I think it does. To see my archives.php page it in action, just head over to the Ikiru Demo Blog and look at it on any of my themes. (You can also see the Archives page on WordPress’s default theme for comparison.)
And if you’re looking for something even more fancy than the Archives pages provided by Smart Archives (in or outside of) my themes, I’d suggest that the best place to look is Clean Archives which is both flashier and larger than the Smart Archives plug-in. Though these characteristic were detrimental to my need here, they may be exactly what you’re looking for.
One Theme at a Time
This is more a note to myself than anything else, but I bet some other aspiring WordPress theme designer will make the same error sometime, so it’s becoming a short tutorial.
OK, so here are the steps you should follow:
- Make one WordPress theme. Be completely satisfied that nothing is missing from it and nothing is superfluous. Then move on to another theme.
And you’re done. Pretty neat, huh?
If you’re wondering why I feel the need to make a tutorial for something so obvious, consider my process:
- Make one WordPress theme (BWO). Get it to OK, but fail to add all that’s necessary and remove all that is not.
- Make a theme that’s based on the original (BWO_doodle).
- Revise original theme by adding some things it was missing.
- Make more themes based on the original, in my case four: BWO_one, BWO_space, BWO_invert, Carter’s Line.
- Revise original theme, improving search.php and archives.php; removing the unused and unnecessary files (comment-popup.php, attachment.php, links.php).
- Realize that these changes are important enough to by made in all previous version of the theme.
- Spend far too much time making those changes to the previous versions.
- Write a tutorial (another waste of time) about your foolishness.
I should also be clear that this is a (slight) oversimplification of the process. It glosses over the large number of alterations (usually but not always to the stylesheet) that’s I’ve had to make as well.
I guess this is probably part of the learning process, but it’s making me feel completely silly.
