How to stop post duplication when using multiple WP_Query() requests

Filed February 12th, 2012 under Tutorial, WordPress

On my site SalaciousSound I have two selections of articles: five ‘featured’ posts which appear at the top of my index, above the fold, and ten more of my most recent articles.

I wanted to exclude the featured articles from appearing in the regular articles section, and I did so by using the WP_Query() parameter ‘post__not_in’.

The reason for writing this article is that collecting the post IDs from my first WP_Query and passing them to the second was, for me, non-trivial because the five featured articles appear in my header.php file and the ten regular articles appear in index.php.

In order to achieve my desired result I had to set a php variable in my functions.php file, and then declare it as a global variable in my header.php file and index.php file.

Here’s how the relevant code looks:

from functions.php
$featIDs = array();
from header.php
global $featIDs;
$feats_query = new WP_Query('category_name=Features&posts_per_page=5');
while ($feats_query->have_posts()) : $feats_query->the_post();
	array_push($featIDs, $post->ID);
from index.php
global $featIDs;
$index_query = new WP_Query(array( 
	'posts_per_page' => 10, 
	'post__not_in' => $featIDs
));
Comment! (2)

How to use WP_Query() with pagination

Filed February 12th, 2012 under Tutorial, WordPress

It turns out using WP_Query() AND paginating your results properly is not entirely straightforward. The WordPress Codex documentation and information on the help forums is also pretty bad.

This article explains how to make custom queries using WP_Query() AND still allow for pagination.

My use case is: a custom query on my index page which excludes certain posts, and wp_pagenavi for paginating my archives.

I explain in detail why I am using WP_Query() instead of the regular WordPress loop in my next article ‘How to stop post duplication when using multiple WP_Query() requests‘.

In short, WP_Query doesn’t know what page you’re on like the regular WordPress loop does – you need to tell it which page of posts to ask for (and, in addition, how many posts per page you want it to retrieve).

Here’s the relevant code:

$pagedNum = get_query_var('paged');
$index_query = new WP_Query(
	array( 
		'posts_per_page' => 10, 
		'paged' => $pagedNum
	));
Comment! (0)

WPAudio WordPress Plugin Crashes Safari Browser When Song is Played From Post

Filed July 3rd, 2011 under Tutorial, WordPress

I encountered a problem on my music blog SalaciousSound today. I use a plugin called wpaudio, which uses javascript and the soundmanager2 library (with flash fallback) to play mp3 audio files. I was finding that, on a particular post, whenever I played an mp3 the browser would crash. The plugin was working fine on all other posts, so I knew that this had something to do with the number of mp3 files on this particular post.

How to reproduce the crash

Create a post with more than 20+ mp3s to play, or go to a page (archive for example) where more than 20+ players are present – it doesn’t matter if they’re all inline or each have their own wpaudio markup, you just need more than twenty players. The crash was occurring in Safari. Chrome was working ok. I didn’t test Firefox or Internet Explorer.

I have a monthly series that I run called the Monthly Best of the Blogosphere, wherein I post 25-30 tracks that have been really popular that month. Only on these posts was the browser crash occurring.

How to fix the crash

You have to edit the wpaudio.js (or wpaudio.min.js file, depending on what you use – I use the minified wpaudio.min.js file myself). You have to change two lines of code in this file, and add an additional one. It’s pretty easy, and if you follow my instructions carefully you can do this with minimal coding knowledge.

Find this function:

function WpaudioHTML5 (parent) {
			...
}

Find these two lines – they are sequential:

start = player.seekable.start();
end = player.seekable.end();

Change them to this:

start = player.buffered.start();
end = player.buffered.end();

Next, find these two lines:

player.src = parent.getUrl();
player.volume = 1;

And add this line after them:

player.preload = "none";

Voila! Problem solved!

Comment! (0)

How to Use WordPress Multisite Subdomain Install With Real Subdomains

Filed January 10th, 2011 under Tutorial, WordPress

TL;DR: I added the VirtualHost record for specialsubdomain.mysite.com BEFORE the mysite.com record, and inserted the “Include /var/www/vhosts/mysite.com/conf/vhost.conf” statement in to the last line of the mysite.com VirtualHost record (just before the closing tag).

My frustrating learning experience

I just sorted out an issue with wordpress multisite, and it took quite a bit of searching and reading to uncover what is ostensibly a very simple solution. Admittedly, I didn’t know anything about the httpd.include or vhost.conf files before I set out a few weeks ago, nor the ServerAlias tag the VirtualHost tag or how dns entries, including the wildcard (*) are parsed.

The problem was this: wordpress multisite is installed with a subdomain install. That means every site created gets a new subdomain, and as a result you need a way to tell your server that any traffic that goes to that subdomain should ask the main site for information and files.

The practical solution is to use a wildcard dns (*) entry when setting up wordpress multisite – indeed this is the definitive proscribed solution. Unfortunately, this can cause some headaches if applied incorrectly, as has been well documented in this discussion thread.

What was supposed to happen

1. People can visit mysite.com
2. I can create a new site (a subdomain) in the mysite.com backend, and people can automatically access newsubdomain.mysite.com
3. People can access my subdomain community.mysite.com which is NOT a wordpress multisite blog, and any other special subdomains that I might like to define separately from the mysite.com wpms install (ie community is vanilla forums, and I might want to add some kind of mail redirect to google apps email mail.mysite.com)

What was happening when I included the vhost.conf file

1. I followed the instructions to add a line to my httpd.include file which includes a vhost.conf file. Incidentally, this is ALSO required for domain mapping, which I am also doing:

<VirtualHost xxx.xxx.xxx.xxx:80>
   ServerName   mysite.com:80
   ...
   Include /var/www/vhosts/mysite.com/conf/vhost.conf
</VirtualHost>

2. Because the vhost.conf file was included INSIDE the VirtualHost tag, the VirtualHost tag was NOT required in the vhost.conf file. All I required was one line: ServerAlias *.mysite.com
3. I could visit mysite.com
4. I could visit my wpms subdomains
5. I couldn’t visit community.mysite.com – I would be redirected to a page telling me that registration is closed (and presumably I would have been redirected to a signup page, were I to enable that feature)

What was happening when I took out the vhost.conf file

1. I could visit mysite.com
2. I could visit community.mysite.com
3. I couldn’t visit any of my wpms subdomains

The solution, and why

It took a minute, but when I paid attention to the details of the discussion thread the answer was pretty clear.

The way these dns redirects work is in order – the text file is just parsed, and apache takes the first valid option it finds. “Cool!” I thought, “that just means that I need to order my file properly!” Sure enough, once I added the VirtualHost record for community.mysite.com BEFORE the mysite.com record, and put the include vhost.conf statement in to the mysite.com VirtualHost record, things worked fine!

Voila:

<VirtualHost xxx.xxx.xxx.xxx:80>
   ServerName   specialsubdomain.mysite.com:80
   ...
</VirtualHost>
<VirtualHost xxx.xxx.xxx.xxx:80>
   ServerName   mysite.com:80
   ...
   Include /var/www/vhosts/mysite.com/conf/vhost.conf
</VirtualHost>

I hope this helps even one person, because I was seriously going nuts with this problem. Please feel free to comment if there is any confusion over what I’ve described here, but keep in mind that I am still a novice with Apache… but I’ll try my best! :)

Comment! (1)

An (Almost) Complete Guide to CSS3 Color

Filed January 2nd, 2011 under CSS, Tutorial

Color is a fundamental principle of design. The right color, in the right place, and the right time can solidify the emotional appeal of a brand. It’s not surprising then that the color module would be one of the key improvements CSS3 makes over the previous version.

Unlike the previous articles in this series, this An (Almost) Complete Guide will focus on some of the more technical aspects of the CSS3 color module, in addition to an overview of the practical applications of opacity, HSL, HSLA, and RGBA.

Read the rest of this entry »

Comment! (2)

An (Almost) Complete Guide to CSS3 Borders & Backgrounds

Filed October 4th, 2010 under CSS, Tutorial

Borders and backgrounds are two of the most essential CSS elements. They are part of the groundwork that allow us to create aesthetically rich user interfaces, and help make the web a beautiful place to be.

But CSS2.1 has proven inadequate in a number of respects. Remember the rounded corners fad (we even use it on kmsm.ca)? For a long time, that was driven via div and image hacks – creating lots of unnecessary and unpleasant code. CSS3 adds native support for these types of elements. In this guide, I provide an overview of the borders and backgrounds module in clear, easy-to-understand language.

W3C Specification: http://www.w3.org/TR/css3-background/

Browser Specific Support

WebKit support: Strong

Firefox support: Strong

IE9 support: Medium

Backgrounds

Let’s dig right in.

CSS3 introduces two new important elements to backgrounds: multiple images, and background size. In brief, multiple backgrounds is exactly as it sounds: you can layer multiple backgrounds in a single box. Before the advent of CSS3 this had to be done using a combination of layered divs. Thankfully, that’s changed.

Multiple backgrounds

Each box has a background layer that may be fully transparent (the default), or filled with a color and/or one or more images.

W3C Specification

To create a box with multiple backgrounds, we simply define them in a comma-separated list using the background-image element. All other assigned properties, such as background-position require similar comma-separation. For example:

#multipleBackgrounds {
	background-image: url(flower.png), url(ball.png), url(grass.png);
	background-position: center center, 20% 80%, top left;
}

In this case, we’ve got an image of a flower located in the middle of the box, layered over a ball located 20% from the top and 80% to right, layered over grass located in the top left. Stories in Flight has a particularly good working version of exactly this example: CSS Multiple Backgrounds.

Now, this might not seem like much – after all, you can always layer images in Photoshop – but it creates really interesting possibilities when combined with other CSS3 techniques (i.e. gradients). Imagine, for example, that you want to create a repeating background of a texture – but also have the page slowly fade to black as it approaches the bottom of the screen. With CSS2.1, this was possible only by first creating a repeating image of the texture, placing it in a div, and layering a secondary div over top, which itself has a horizontally repeating image of a gradient. Now, we can use a single div, and define both backgrounds at once (and even skip creating an image of a gradient altogether).

Oh and one last note: no vendor prefixes are necessary!

Background size

Let’s say you’d like to dynamically resize the background for the body element of a page – such that the background image is always proportionally scaled to the size of the browser window. CSS3 makes this easy. We’ll have to use some vendor prefixes though.

#backgroundSize {
	-webkit-background-size: cover;
	-webkit-background-size: cover;
	background-size: cover;
}

Alternatively, we can use contain to limit the background to the inside of the background positioning area (an area you can define in a couple of different ways using background-origin).

Another interesting technique for background-size is defining it as 100%. We can achieve some really cool effects this way. Peter Gasston covers one such example in his article Liquid Faux Columns with Background-Size.

Borders

Border image

As one of the less intuitive new elements in CSS3, border-image is prone to confusion. I’ll try and clear that up.

We start by defining an image, where the image should be sliced horizontally and vertically, and end by declaring a type (repeat, round, stretch). Again, we’re going to have to use vendor prefixes:

#borderImage {
	-moz-border-image:url(border.png) 20 20 round;
	-webkit-border-image:url(border.png) 20 20 round;
	border-image: url(border.png) 20 20 round;
}

Let’s break this down visually. In the image below, we see border.png on the left. We’ve sliced it vertically (slice a) at 20px, and sliced it horizontally at (slice b) at 20px. The image is then used as the border, and repeated along the slice lines. Note that you define up to four slices, in the canonical directions (top, right, bottom, left).

As you can imagine, there are some really innovative applications in store for this element. lrbabe.com has some excellent examples of potential applications for everything from multi-state buttons to tabs.

Border radius

That brings us to border radius, perhaps the most welcome element in the borders & backgrounds module.

We’re going to have to use some vendor prefixes again, but that’s okay – we’ve been dying to be able to do this natively for so long, it hardly matters. And it’s really as easy as could be. First, define a border in the typical way (size, type, color), then define a border-radius:

#borderRadius {
	border: 5px solid #000;
	-moz-border-radius: 15px;
	-webkit-border-radius: 15px;
	border-radius: 15px;
}

In this example a radius of 15px will be applied to each corner (top left, top right, bottom left, bottom right). But we’ve also got fine control of each corner:

#borderRadius {
	border: 5px solid #000;
	-moz-border-radius-topleft: 15px;
	-moz-border-radius-topright: 0px;
	-moz-border-radius-bottomright: 15px;
	-moz-border-radius-bottomleft: 0px;
	-webkit-border-top-left-radius: 15px;
	-webkit-border-top-right-radius: 0px;
	-webkit-border-bottom-left-radius: 0px;
	-webkit-border-bottom-right-radius: 15px;
	border-top-left-radius: 15px;
	border-top-right-radius: 0px;
	border-bottom-left-radius: 0px;
	border-bottom-right-radius: 15px;
}

And with that, we say goodbye to everything from div hacks, to JavaScript, to images in order to get those oh so fashionable rounded corners.

Box shadow

One other interesting new feature from this module is box shadow. Again, it’s simple, straightforward, and clear. To apply a shadow to a box – say a div – we define a horizontal offset, a vertical offset, an optional blur distance, and a color. For example:

#boxShadow {
	width: 100px;
	height: 100px;
	box-shadow: 15px 15px 5px #000; 
}

This produces a 100px square box, with a black shadow 15px horiztonally and vertically offset with a 5px blur. I mentioned it was easy, didn’t I?

Other Resources

Quirksmode: Backgrounds

Introduction to CSS3 – Part 6: Backgrounds

This article is part of a series on CSS titled An (Almost) Complete Guide to CSS3 regularly posted biweekly at kmsm.ca. If you enjoyed this article, you might also enjoy An (Almost) Complete Guide to CSS3 Multi-Column Layouts.

Comment! (10)

An (Almost) Complete Guide to CSS3 Multi-column Layouts

Filed September 20th, 2010 under CSS, Tutorial

One of the defining features of print design is the ubiquity of multi-column layouts. And there are a couple of good reasons why this is the case.

First of all, it’s generally easier to read lines of text between 8 and 12 words long. Second, it’s easier to control the amount of negative space in a layout with columns. For a long time, this was the primary advantage of print but CSS3 makes multi-column layouts possible online (and without the need for JavaScript).

W3C Specification: http://www.w3.org/TR/css3-multicol/

Browser Specific Support

WebKit support: Strong

Firefox support: Strong

IE9 support: None

The multi-column model

The WC3 specification introduces a number of new properties that allow us to define columns in HTML layouts. Just like print designs of old, we’re able to define the number of columns, column width, column gaps, and even rules governing overflow.

Essentially, the specification states that a multi-column element needs to have either a defined column width or column count. Browsers are supposed to render these elements similar to the way they render tables – but the content in a column layout is dynamically split into blocks.

At the moment, we’re not able to define certain properties about columns (like column-specific backgrounds), but it’s possible this might change.

The number and width of columns

column-count and column-width are the two most basic ways to define the properties of a multi-column element.

column-count

By default, column-count is set to auto. This means that if we explicitly define the column-width, the browser will sort out for itself how many columns are necessary to populate the content in the multi-column element. Obviously, that’s not always desirable so we’ll want to explicitly define the number of columns to span the content across. And it’s easy to do:

#multicolumnElement {
	-webkit-column-count: 2;
	-moz-column-count: 2;
	column-count: 2;
}

column-width

As I mentioned, we can define column-width without defining the number of columns, and the browser will render our content dynamically (there are some fine controls available too – keep reading for those). To define column-width, we can use any of the units regularly available to CSS properties (em, px, %, etc).

#multicolumnElement {
	-webkit-column-width: 15em;
	-moz-column-count: 15em;
	column-count: 15em;
}

Of course, we can always combine column-width and column-count:

#multicolumnElement {
	-webkit-column-count: 2;
	-moz-column-count: 2;
	column-count: 2;
	-webkit-column-width: 15em;
	-moz-column-width: 15em;
	column-width: 15em;
}

Column gaps and rules

All print designers are familiar with column widths and gaps, but web designers are addicted to the language of margins and padding.

But column gap is exactly as it sounds – the size of the space between columns defined in any unit regularly available in CSS (em, pixel, etc).

column-gap

The WC3 specification defines 1em as the default column-gap value, so we’ll use it in this example:

#multicolumnElement {
	-webkit-column-gap: 1em;
	-moz-column-gap: 1em;
	column-gap: 1em;
}

column-rule

Column rule is another throwback to the print era. Basically, column rules are thin lines between the columns, to further aid readibility and/or to distinguish between separate stories. CSS3 gives us three different properties for the column rule: column-rule-size, column-rule-style, and column-rule-color, but we can use the shorthand column-rule to declare values for all three at once.

As you might have guessed, the regularly available units, styles, and color values can all be used:

#multicolumnElement {
	-webkit-column-rule: 1em solid #000;
	-moz-column-rule: 1em solid #000;
	column-rule: 1em solid #000;
}

Column breaks

What if I want to break the column before an h3 tag, you ask? Well, that’s easy too. CSS3 gives us the column-break property with a number of possible related properties and values, including: auto, always, avoid, left, right, page, column, avoid-page, and avoid-column.

column-break

So if we want to break the content before every h3 tag we simply include the column-break-before property in our stylesheet:

h2 {
	-webkit-column-break-before:always;
	-moz-column-break-before:always;
	column-break-before:always;
}

Spanning columns

If we want an element, say a headline, to span across multiple columns we can make use of the new column-span property.

column-span

column-span has two possible values: all, and regular numbers (e.g. 1,2,3). Defining column-span as all means that the given element will span across the whole multi-column block, while assigning it a regular number will limit its span to that number of columns:

h2 {
	-webkit-column-span:all;
	-moz-column-span:all;
	column-span:all;
}

h3{
	-webkit-column-span:2;
	-moz-column-span:2;
	column-span:2;
}

Filling columns

Just like print design, we might want some finer control over how columns are filled with content. CSS3 introduces column-fill to give us that kind of control.

column-fill

We can either define a value of auto or balanced. The former will sequentially fill columns with content, while the latter evenly distributes the content.

#multicolumnElement {
	-webkit-column-fill:auto;
	-moz-column-fill:auto;
	column-fill:auto;
}

Demo!

To cap things off, I’ve created a quick demo project based on the first few paragraphs of Moby Dick. It should display correctly in both WebKit and Mozilla based browsers (though it’s not formatted properly for mobile).

Click here for a live preview or click here to download the project files.

Other Resources

Introducing the CSS3 Multi-Column Module by Cedric Savarese

Remembering: The CSS3 Multi-Column Layout Module by Web Designer Notebook

Comment! (58)

How To Find and Optimize Fragmented Tables in a MySQL Database

Filed July 13th, 2010 under Tutorial, Web Technologies

I’ve been doing some database optimization lately, and I found this script super handy. It will find any fragmented tables in your database:

select TABLE_NAME,Data_free
from information_schema.TABLES
where TABLE_SCHEMA NOT IN ('information_schema','mysql')
and Data_free > 0;

Once you have found your fragmented tables, you can optimize them with this handy piece of code:

optimize table %TABLENAME%
Comment! (0)

How To Make Timthumb Get Youtube and Vimeo Video Thumbnails, Add Default Thumbnail When No Images Are Present

Filed July 6th, 2010 under Tutorial, WordPress

One of our main portfolio pieces is a music blog called SalaciousSound that I started about 2 years back. I’ve been using timthumb on the site for about 6 months, though when I first added it I wasn’t able to grab thumbnails for videos, and it also didn’t handle posts without images well. I’ve added two pieces of functionality to the function that calls timthumb, catch_that_image(), which resides in my theme’s functions.php file. The former grabs thumbs from videos as the title describes, and the latter just adds a default image that I have defined if the function can not find an image or a video to get a thumbnail from.

function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('//i', $post-&gt;post_content, $matches);
$first_img = $matches [1] [0];
if ( $first_img != '' ) {
return urlencode($first_img);
}
/*
$match = array();
preg_match("/http://www.youtube.com/v/([^"][a-zA-Z0-9-_]+)[&amp;"]/siU",$post-&gt;post_content,$match);
if ( $match[1] != '' ) {
return 'http://img.youtube.com/vi/'.$match[1].'/0.jpg';
}
$vimmatch = array();
preg_match('@vimeo.com/[^"&amp;d]*([^"&amp;]+)@i', $post-&gt;post_content, $vimmatch);
if ($vimmatch[1] != '') {
$vimhash = unserialize (file_get_contents ("http://vimeo.com/api/v2/video/".$vimmatch[1].".php"));
return $vimhash[0]['thumbnail_medium'];
}
*/
else { return 'http://url.com/wp-content/themes/themefolder/images/defaultimage.png'; }

}
Comment! (2)