Words

Custom WordPress Post Queries & Meta Data Part 2

In part one we got to grips with WP_Query and and kept our custom queries pretty simple, but what if we want to display posts that meet one or two conditions set by custom fields in the admin area?

Querying By a Single Custom Meta Field

In part one we imagined a website with a custom post type for album reviews – now let’s imagine we only want to display reviews that have received a score of 5. I’ve included comments for each line to explain what’s happening:

1
2
3
4
5
6
7
8
9
$args = array( // Create our arguments array
‘post_type’ = ‘review’, // specify the type of post we want to query
‘meta_query’ = array( // Tells WordPress to query meta data using the arguments in this array
key= ‘score’, // Name of the meta field
‘value’ =5, // The value to be used in our query
‘compare’ ==, // How the post’s meta should compare to our value
‘type’ = ‘NUMERIC’ // The data type to expect
)
);

Querying by two Custom Meta Fields

In this example we want to return posts that have a score of 5 and are listed under the genre ‘rock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$args = array(
‘post_type’ = ‘review’,
‘meta_query’ = array(
'relation' = 'AND', // Logical operator - we want both of the following to be true
array(
'key' = 'score',
'value' = '5',
'compare' = '=',
'type' = 'NUMERIC'
),
array( // Second array - holds the arguments we also want to use
'key' = 'genre',
'value' = 'rock',
'compare' = '='
)
)
);

I hope now you can see how extending the theory shown here you can create more advanced queries. While these posts focused largely on custom meta data, there are plenty of other options for querying posts, such as post meta information & taxonomies. For a full breakdown of what’s possible I’d recommend visiting the WordPress WP_Query Codex page.

Custom WordPress Post Queries & Meta Data

Working on a project recently that required some advance querying of posts it became obvious that there was no clear instructions on querying WordPress posts by custom meta data – something anyone who’s customised  WordPress will no doubt have used.

It’s easy enough to get and display the meta data of a particular post but returning posts that match specified meta quires isn’t as well known, but once you get to grips with it you’ll see how the principals can be expanded to build complex WordPress based websites such as eCommerce stores or property websites that require advanced filtering.

Note: if you are comfortable with WP_Query and are looking for specific examples on querying custom meta data click here to visit part 2

Understanding WP_Query

A bare bones but recognisably standard WordPress loop may look like this:

1
2
3
4
5
6
7
8
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<h1><?php the_title() ?></h1>
<div class=”post”><?php the_content() ?></div>
<?php endwhile; else : ?>
    Sorry, I couldn’t find any posts for you.
<?php
  endif;
?>

The above loop would be fine for a single.php or page.php template but it offers virtually no control over which posts are displayed. The solution then, is to use WP_Query which separates the query and the loop.

Using WP_Query

Let’s assume we have a custom post type called ‘review’ for album reviews on the website and we only wish to display these type of posts on a particular page.

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$args = array(‘post_type’ => ‘review’);
$reviews = new WP_Query($args);
if ($reviews->have_posts()) : while($reviews->have_posts()) : $reviews->the_post();
?>
    <h1><?php the_title() ?></h1>
    <div class=”post”><?php the_content() ?></div>
<?php endwhile; else : ?>
    Sorry, I couldn’t find any posts for you.
<?php
    endif;
?>

As you can see, much of the above is the same as the original loop – the difference comes at the start where we’re querying the database for certain posts.

Let’s look at it line by line:

$args = array(‘post_type’ => ‘review’);

Here we create a variable that holds an array of key – value pairs that WordPress will try to match when retrieving posts. WordPress allows for a range of arguments here but we’re starting simple – we want posts where the type is recorded as ‘review’.

$reviews = new WP_Query($args);

In this line we’re instantiating the WP_Query class and passing it the query we’ve built in the $args variable above. We place this instance of the class WP_Query in a variable so we have something to reference further down.

if ($reviews->have_posts()) : while($reviews->have_posts()) : $reviews->the_post();

The only difference between this line and the original loop is we’re referring to methods within the specific WP_Query class we want and to ignore any others. As WP_Query is held in the variable $reviews, we specify as much and tell PHP were to look. Essentially we’re saying:

Look inside $reviews and access its method ‘have_posts()’.

Next Steps

In our example we’re only using the title and content template tags but you’re free to access any of the usual tags such as author, published date, category etc.

Note that WP_Query works on non-custom meta data just as well. If you wanted to display posts in a particular category the following would be fine:

$args = array(‘cat’ =>1);

So far we’ve kept our queries pretty simple, only including one argument at a time, but what if we want to query posts by the values of custom fields?

Next: Querying Posts By Custom Meta Data

Understanding CSS Positioning: Absolute

Positioning of elements in CSS is one of the harder things to fully understand to those new to creating layouts. In some cases no positioning declarations are needed at all to achieve the desired layout but when they are, getting it right can be a little confusing.

In this article I hope to provide an example that not only explains absolute positioning but can be used in your own layouts where you may otherwise have been struggling. While I’ll touch on the theory behind absolute positioning, I’ll leave a detail explanation to this excellent article from Steven Bradley which I would strongly urge you to read, even if you think you’ve got a good grasp on CSS positioning.

 

Positioning a ‘buy now’ tag over a div or image

The idea here is to position a small tag overlaying the top right of a sibling element. Let’s imagine we have a book we’re promoting and we’d like to add a promotional tag over an image of the book cover.

Let’s start with some basic markup and styling:

http://jsfiddle.net/tom_collinson/WGrv3/

All the elements we need are there, but the tag is sitting above the book cover, rather than overlapping it as we want.

 

Absolutely position the promo-tag

If no elements within the document have defined positions they work against the document itself which is effectively set to position: static. This follows the ‘normal document flow’ and is defined by the box model.

We need to add a position declaration to the promotional tag to put it in a position not dictated by the normal flow – position: absolute will give us the ability to place the tag exactly where we want by taking it outside of the flow completely. We know we want the tag overlaying the top right of the book cover so let’s give it a position of right: 0;

This says; absolutely position the element 0 pixels from the right.

How does that look?

http://jsfiddle.net/tom_collinson/E8KD9/

Not great. The promotional tag is doing exactly what we’ve told it too but not what we want, so what are we missing?

The ‘Cascading’ in ‘CSS’ explains exactly what’s going on here. We’ve told the promotional tag to be absolutely positioned but we haven’t specified what that’s in relation too, so the browsers will assume it’s the document itself.

The Solution

We’ll need to assign a position: relative declaration to the parent element, in this case ‘book’.

This tells the browser that child elements of ‘book’ should be positioned relative to it, rather than the document if they have any position declaration themselves. It also tells the browsers to relatively position ‘book’ to its parent – in our example that’s body but in more complex layouts that will differ.

How does that look?

http://jsfiddle.net/tom_collinson/Cuemz/

Perfect!

So, to recap:

  • Buy-tag is set to be positioned exactly where told, ignoring the normal flow.
  • Book has the position: relative declaration, ensuring child elements are positioned relative to it rather than the document.

Writing for Startups.co.uk

Over the last few months I’ve written a few pieces for Startups.co.uk, a website dedicated to helping new businesses get up and running. There are a few more articles in the pipeline but for now here’s a few links!

Pinterest For Business: What You Need to Know

As one of the fastest growing sites in history, Pinterest has become a buzz topic for those of us in the marketing world wondering how, or even if, it can be used as a marketing and promotional tool for businesses. The answer is a resounding yes – as long as your business appeals to the audience and you have a clear approach for engaging with the network and its users.

(more…)

Got hit by Penguin? It’s probably your own fault

Having been involved in SEO for several years now I have come to know about both white and black hat techniques used to raise your rankings in the SERPs.

What many people I speak too often overlook is the fact that Google search is a product offered by a business. We as website owners use this service to make money , either through the AdWords platform or by appearing in the organic search results. As the owner of the product, Google have every right to make changes the deem beneficial to their business and unless you’re an AdWords user you have no ‘right’ to feel aggrieved if an algorithmic change like Panda or Penguin negatively impacts your website’s traffic.

(more…)

How Google’s Secure Search Will Affect Your Website

A post of mine has just been published over on the Digital Clarity blog regarding the Google announcement that logged in users will be redirected to the secure .com search, what it means for you and what may happen in the future. You can read it here and leave a comment if you’d like.

Online Checkout – In Real Life, An actual funny video from Google.

I wish this was completely made up and ludicrous but there are many sites out there that still make you jump through hoops like this to make a purchase! Web designers, developers and owners –  hear these words and take heed. The shopping process should be designed for the customer not for your internal processes!