I'm doing a site for a wine importer.
I've set up two custom post types: WINES and VINEYARDS.
The wines have a taxonomy of WINERY, which corresponds to the VINEYARDS post type.
So I want the VINEYARDS page to have a list of wines they produce, pulled from the taxonomy WINERY.
Here's the template code that does that (except for the problem line: "VINEYARD-NAME-HERE" SHOULD be the slug):
<ul>
<?php
$args = array(
'post_type' => 'wines',
'winery' => 'VINEYARD-NAME-HERE'
);
$wineslist = get_posts($args);
foreach($wineslist as $post) :
setup_postdata($post);
?>
<li><a href="<?php the_permalink(); ?>" id="post-<?php the_ID(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
That works fine except of course, I'm hand-coding the "vineyard-name" slug and building a new page template for each vineyard. Address of the vineyard page is like this:
/vineyards/vineyard-name-here/
I'm sure there's an easier way. Care to help?
I've set up post types and taxonomies with the Custom Post Types UI Plugin, if that makes any difference.
Thanks in advance.
Maor Barazany answers:
Try this one, put this before the $args array -
$uri = $_SERVER["REQUEST_URI"];
$tmp = explode ('/', $uri);
$vineyard_name = $tmp[sizeof($tmp)-1];
First line will retrieve the uri (which is , as you said is - /vineyards/vineyard-name-here/)
Second line will split it to a temporary array by the / sign, the the last element of that array will hold the "vineyard-name-here" you need, taken from the actual url is being viewed.
Then, the last line will assign this to a variable named $vineyard_name that will be dynamically changed according to the page being viewed.
Then you can use it like this:
$args = array(
'post_type' => 'wines',
'winery' => $vineyard_name
);
Jim Dugan comments:
That's so close! But it gives me a list of wines from ALL vineyards. So to see what the variables were giving me, I echoed it out. That told me there was something not quite right about "sizeof($tmp)-1" But with a little trial and error:
$vineyard_name = $tmp[3];
did the trick. Thanks!
Mike Truese answers:
Perhaps a page-w-posts type of template, where you can add a custom field for the 'vineyard' when you define the page, and that is used to pull the proper posts.
This also gives you the ability to add a blurb/logo at the top of the page about the vineyard itself, which is IMO better than just a straight off list of wines.
The query is hardcoded, but the variable is pulled from a custom field on Vineyard page.
We do this for a recipe site where the recipe cat (soup, salad, etc) is the variable.
Jim Dugan comments:
Yes, the above code is outside the regular loop in a template called "single-vineyards.php"
This template is for any single instance of the post type "vineyard" so that the page for that can have headline, description, pictures, logos, etc.
The code above is, essentially, a secondary loop to show all the wines from that vineyard.