What’s a loop?
When using WordPress, “The Loop” refers to the code in your template files that displays posts. Usually there is only one main loop per page, but you can have secondary custom loops to show special content. These can include recent posts and related posts.
The loop depends on queries
A query is related to the loop in that it determines what should be shown in the loop. For example, the default home query will contain all posts, 10 per page (or whatever number is set in Settings > Reading), from all categories; a single post query contains only information for the post or page you are viewing; archive loops will have posts according to the kind of archive page you are on (category, tag, month etc).
Default and custom queries
The main query for a WordPress page is determined automatically by the type of page you are viewing (it’s all handled by WordPress). You can create a custom query out of the default query by using the following PHP code somewhere before the start of your main loop code.
global $query_string;
query_posts($query_string . '&cat=-5');
The above code gathers the variable $query_string
, which contains all the default query information and then uses query_posts()
to create a query with all of the features of the default query, except the attributes that you change. In the example I have excluded the category with an ID of 5 from the query.
The benefit of using $query_string
in this way is that you don’t destroy page pagination on the home and archive pages, which will happen when using query_posts()
by itself.
The Loop code
The main loop code generally starts with something like <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
. Where have_posts()
is a WordPress function that determines whether the current query has any posts in it. while ( have_posts() )
says “as long as there are posts in the query, do the following things”, and this repeats for each post until there are no more. In this case “the following things” are to execute the function the_post()
, which fetches the post data from the database and makes it accessible for use via Template Tags, some of which are only available inside the loop.
Creating a custom loop
If you which to access other posts (to create a recent, related, popular or featured post list, for example) while keeping the main loop in tact you need to create a secondary custom loop. The best way to do this is to create a new query, using the WP_Query()
function, which will be completely separate from the main query. Then you may loop over the posts in your new query.
New query for the custom loop
WP_Query()
accepts the same parameters as query_posts()
, so have a look at that Codex page to find out what parameters you need.
For this example, let’s query 5 random posts from a category called “Featured”.
$custom_loop = new WP_Query('showposts=5&category_name=Featured&orderby=rand');
Custom loop code
Now we have to loop over the posts in the new query. Since the original page query still exists and our new query is stored in the variable $custom_loop
we can’t use the same code as the main loop, but it is similar. This loop is basically the same as the main loop code, but it checks our custom query variable $custom_loop
for the posts.
if ( $custom_loop->have_posts() ) :
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
// this is where we put the code to show what we want for each post
endwhile;
endif;
Content for the custom loop
Unless we replace // this is where we put the code to show what we want for each post
with something, nothing will actually show up when we run this code.
One of the simplest (and useful) things we could do is create a list of linked post titles.
if ( $custom_loop->have_posts() ) :
echo '<ul>';
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
echo '</ul>';
endif;
Note that because the code between while
and endwhile
gets repeated for every post, <ul>
and </ul>
(which start and end the unordered list) need to go outside of that part, i.e. outside of the loop.
Putting it all together
The complete code for a custom query and custom loop producing an unordered list of random featured post title link is:
$custom_loop = new WP_Query('showposts=5&category_name=Featured&orderby=rand');
if ( $custom_loop->have_posts() ) :
echo '<ul>';
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
wp_reset_query();
echo '</ul>';
endif;
This is all PHP code, so make sure that you are in a PHP environment, i.e., this code should be somewhere after <?php
and before ?>
. If these bits aren’t in your file where you want the custom loop to go, you can wrap the code in them.
Towards the end I’ve added wp_reset_query()
, which — as the name suggests — resets the query. For some reason, when using new WP_Query()
, endwhile
ends the loop, but not the custom query. There’s another method on The Loop codex page, but it hasn’t always worked for me.
Sometimes I find that wp_reset_query()
doesn’t quite work the way I want it to, I don’t get back to the original query. If you have that problem try if ( have_posts() ) { while ( have_posts() ) { the_post; } };
. That usually works for me to reinitiate the original loop, but I’ve seen it create a recursive post loop too, so be careful.
Using the custom loop in Thesis
Using the custom loop in Thesis is pretty simple (once you have a grasp on the less simple stuff above): all you have to do is wrap the above code in a function and hook it in. If you need more info on basic function syntax check out What are hooks and how do you use them? and The basic anatomy of a custom function on the Tech for Luddites blog.
function custom_featured_posts() {
$custom_loop = new WP_Query('showposts=5&category_name=Featured&orderby=rand');
if ( $custom_loop->have_posts() ) :
echo '<ul>';
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
wp_reset_query();
echo '</ul>';
endif;
}
add_action('thesis_hook_after_post','custom_featured_posts');
That code pasted into custom_functions.php will add a list of 5 random posts from a category called “Featured” to the bottom of every post.
If you only wanted to show it on single post pages you would use a conditional tag by adding if ( is_single() ) :
after the first line that opens the function, and endif;
before the last curly bracket that ends the function.
Add it to the sidebar
If you want to add it to the sidebar to look like your other sidebar widgets you can use the following function.
function widget_featured_posts() {
$custom_loop = new WP_Query('showposts=5&category_name=Featured&orderby=rand');
if ( $custom_loop->have_posts() ) :
echo '<li class="widget widget_featured_posts">';
echo '<h3>Featured Posts</h3>';
echo '<ul>';
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
wp_reset_query();
echo '</ul>';
echo '</li>';
endif;
}
add_action('thesis_hook_before_sidebar_1','widget_featured_posts');
The function has the widget code and a heading added to match the HTML format of widgets in Thesis.
How about using thumbnails instead of post titles?
Using thumbnails is a bit more attractive and intriguing than a list of post titles (not that a good post title can’t pull people in). If you use Thesis you should know about Post Images and Thumbnails; if you don’t please watch the in-post options video!
There’s a nice little snippet of code that you can use (inside the loop) to fetch the thesis post image or thumbnail:
$post_image = thesis_post_image_info('thumb');
echo $post_image['output'];
Use this in your custom loop like so.
function custom_featured_posts() {
$custom_loop = new WP_Query('showposts=5&category_name=Featured&orderby=rand');
if ( $custom_loop->have_posts() ) :
echo '<strong>Featured Posts</strong>';
echo '<ul class="featured_posts">';
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
$post_image = thesis_post_image_info('thumb');
echo '<li>' . $post_image['output'] . '</li>';
endwhile;
wp_reset_query();
echo '</ul>';
endif;
}
add_action('thesis_hook_after_post','custom_featured_posts');
$post_image['output']
has the whole linked image markup with classes etc. If you just want to fetch the thumbnail URL to add your own HTML around it, use $post_image['url']
.
The following CSS (to be placed in custom.css) will cause the thumbnails to be displayed horizontally next to each other.
ul.featured_posts {list-style:none;} ul.featured_posts li {float:left;}
A related posts query
There are several ways to determine if a post is related to another post, without getting too crazy with it, the simplest and most obvious attributes to use are categories and tags. If you haven’t been using categories and tags on your blog I would say to find a plugin that uses other means to determine relatedness, and don’t try to write your own related posts query (if you’re able to write one not based on categories and tags you probably don’t need this tutorial anyway!).
function custom_related_posts() {
global $post;
if ( is_single() ) :
//stores the original post data
$original_post = $post;
//get the post category
$category = get_the_category();
$cat = $category[0]->cat_ID;
//gather a list of tags
$tags = wp_get_post_tags($post->ID);
$taglist = '';
if ($tags) {
foreach ($tags as $tag) {
$taglist .= $tag->term_id . ',';
}
//start loop and query stuff
$args = array(
'cat' => $cat,
'tag__in' => array($taglist),
'post__not_in' => array($post->ID),
'showposts'=> 5,
'caller_get_posts'=> 1
);
$related_posts = new WP_Query($args);
if ( $related_posts->have_posts() ) :
echo '<ul class="related_posts">';
while ( $related_posts->have_posts() ) : $related_posts->the_post();
$post_image = thesis_post_image_info('thumb');
echo '<li><a class="post_image_link" href="' . get_permalink() . '" title="Permanent link to ' . get_the_title() . '">' . $post_image['output'] . '</a></li>';
endwhile;
wp_reset_query();
echo '</ul>';
else :
echo '<p>Sorry, no posts found</p>';
endif;
}
endif;
}
add_action('thesis_hook_after_post','custom_related_posts');
This adds a list of linked thumbnails of related posts to the bottom of a single post page. I’ve added a couple of comments in there to indicate what’s happening in the code.
The $args = array(...
syntax is just another way of writing out the parameters to use in WP_Query()
. It can be a bit easier for humans to read when using more than a few parameters to put them into an array like that.
The tag__in
parameter indicates that the related post should be tagged with any (but not necessarily all) of the same tags as the current post. post__not_in
is used here to exclude the current post from the query. caller_get_posts
, when set to “1”, means that sticky posts are excluded.
You may notice that I’ve added a link around $post_image['output']
because the whole function will only be shown on a single page, but $post_image['output']
doesn’t output a link on single posts and pages.
Questions?
If you are not sure which WordPress tags to use in your loop or parameters in your query, please check the WordPress codex before asking here:
If you need clarification on a particular bit of the code or it doesn’t work in a particular situation, please let me know and be specific. Thanks!
Oscar says
What a great article. It clarifies a lot of things that I didn’t quite understand before. As always, thanks for such a great and through article!
Marco says
That’s a great post. Useful. Bookmarked!
Erick Patrick says
Each and everyday, friends of mine ask me to clarify the loop in WP to them. Now, I know where I can send them and get a little more free time \o/
Randa Clay says
Thanks for this awesome, clear overview of this functionality. I use it regularly, but I love your related posts idea, along with the thumbnails- very nice.
Rilwis says
This is not new, but it’s detailed. Good article for reference. Thank you.
Greg Nemer says
Hi Kris,
You’re going to get a lot of bookmarks with this article since it is so handy to refer to.
You have a real talent for explaining everything in very good detail.
Thanks,
Kate Foy says
Thanks Kris. Great tutorial post as always, and most helpful in coming to grips with the loop! It’s stashed away in Delicious!
Marc Deschamps says
Great post, i’ll use what i learned here in my actual custom theme for sure!
Thanks 🙂
Craig Sunney says
This looks really low key the way you’ve presented here, but it’s kind of like the Holy Grail from an SEO perspective on creating proper site interlinked (themed) areas. You’re really made it easy to follow. Thanks Kristarella 🙂
Scott says
I got the relate posts script to work but I can’t figure out how to style it to look like my current related posts plugin. If you look at any of my blog posts you can see that the related posts are side by side with the title below the image. Is something like this not going to be possible without the plugin?
kristarella says
Scott — You can do that with this query. The CSS is something like
Then to add the title in you change the line
to
Scott says
That worked perfect. I was totally using the wrong CSS class. I forgot to put custom before related_posts and didn’t think to put ul.
The only thing I notice is that for some posts it shows a bunch of related posts but on some it only shows 1. like my project 365 photos, there are a bunch in the same category but it only shows 1 as related. that’s because of the tags being different?
kristarella says
Scott — Yes, it’s probably because there are not more posts with those tags. You could tweak the way the query defines “related” to only us the category or something if you wanted. Since everyone uses categories and tags differently and writes differently it’s hard to specify one function that will work just right for everyone (without getting more complicated and trying to match words in post content etc).
Scott says
That’s what I figured. Thanks!!
Umesh says
Hi, thanks for the very informative post. I wanted to lists the 5 most recent posts on the index page based on category they fall under, but I want to control the order of appearance of categories. Any suggestions for the best strategy to implement this?
kristarella says
Umesh — I would use
get_categories()
to gather the categories that you want (by using the include or exclude parameters) and in the order you want (by using the orderby parameter) then create anew WP_Query
loop for each of the categories. The basic outline of the code would be:Or if you can’t order them the way you want using the
orderby
parameter (or if you don’t need to access any other category information in the loop) you could manually create an array of category IDs. E.g.,$categories = array(1,2,3,4);
— theforeach
would then cycle through those four category IDs and you would just use$cat
instead of$cat->term_id
in the query.Umesh says
Thank you very much Kristarella.
Rick Anderson says
Wow, that is a very well written and detailed post. Those are excellent examples of how to use wp_query in the context of Thesis. I hadn’t really thought of this before but you could easily use your code to produce a “gallery” of thumbnail images that link back to their posts. – For example, you could use it as a catalog page where each product is a post and the traditional “grid view” of products is produced with your custom query.
Thanks again for all of your contributions to the community.
kristarella says
Rick — Cheers! Yeah, the gallery thing is pretty much exactly what I’m doing with my photoblog archive. Man, I love custom queries!
Thanks for all your contributions in the forum! Great to see people helping each other out!
Jason Coffee says
Maybe you covered this but Is there a way to “call” it on a page so I could add it to my static home page. I would like it to appear in the table next to each video in each category as a list of most recent posts for each category.
kristarella says
Jason — You need to use Conditional Tags. If you’ve created your home page manually in the WordPress editor you can’t really integrate this in the middle of the page, you’d need to copy the contents of your page into custom_functions.php and then add a loop for each category where you want it. Then you wrap the whole contents inside the function with
if (is_front_page()) { ... }
and hook it in withthesis_hook_after_post
.kay says
I love how you explain this stuff. Really helps shorten the learning curve.
I’m really curious as to how they coded their home page for the three featured posts on ArtofBlog
http://www.artofblog.com/
I am wanting to do something similar for my home page but having a hard time wrapping my mind around how I’d get it to work.
thanks!
kristarella says
Kay — Art of Blog has a custom full-width area (similar to the full-width nav area in my full-width headers tutorial), which I suspect contains 3 custom loops getting a post from 3 different categories. I’m not sure whether these are the most recent posts from those categories, or ones tagged with something, or some other way to select them.
You can use the code I showed in this tutorial to get the Thesis Post Image thumbnail, although you can see that their post thumbnails are a different size to the images in the 3 featured posts: they are actually using the WordPress featured image for those particular posts (slightly more complicated to explain, I would go with the Thesis thumb if it suits what you’re trying to do).
Cassie says
Hi Kristarella,
It took me a few reads but I think I get the concept!
I loved how you did your photoblog archive. I’m a CSS newbie so can you explain how to create the grid like you did?
Thanks!
kristarella says
Cassie — The photoblog archive is an unordered list of linked images (using the Thesis thumbnail code, like the above tutorial). To get it in a grid you can simply float all the list items to the left and they will stack together. The minimum CSS you’d need is
Cassie says
Thank Kristarella! I’m thinking about using it as a way of displaying three teasers across my content area. Instead of calling a thumbnail I would call the teaser. Essentially it’d be an unordered list of teasers. Not sure if it’ll work but am going to give it a try.
kristarella says
Cassie — If you’re looking into implementing custom Thesis teasers (and if you want them to use the same format as the usual Thesis teasers), check out this forum thread for a thesis teaser custom loop.
Cassie says
Thanks for pointing out the thread. I don’t really understand the code or if that’s what I’m looking to do but I’ll give it a try. I basically just want three teasers to show on the home page, side by side, like three columns. Seems to be a hard thing to come by!
kristarella says
Cassie — That code won’t do three automatically, but could with a little adjustment. Anywho, good luck, and feel free to ask in the forum thread if you need help with it.
Martin says
Make a css div from 100% x 100% div containing all of the site could accommodate any screen resolution?
Mark says
Thanks for your as always very clear tutorial.
I am trying to put out the title and the except in the same formating as I would normally have in Thesis. But nothing is coming out styled. Following is my code. Could you tell how I could go about that?
function reviews_page() { if (is_page(array(584,’999′))) {$query = array ( ‘posts_per_page’ => 10, ‘cat’ => 84);$queryObject = new WP_Query($query);// The Loop…if ($queryObject->have_posts()) { while ($queryObject->have_posts()) { $queryObject->the_post(); the_title(); the_content(); }}}}remove_action(‘thesis_hook_custom_template’,’thesis_custom_template_sample’);add_action(‘thesis_hook_custom_template’,’reviews_page’);
Mark says
Sorry about the code above, I used the encoding link you specified and I’m not sure what happened…
kristarella says
Mark — You need to add the HTML that goes around the post elements, like the following (inside the loop):
Sorry about the encoder. At some point they made it a default option to encode line endings, which is just unnecessary and ugly in this context, I’ll have to find a different encoder to link to.
Mark says
Thanks a lot, Kristarella.
Mark says
Well, I did as you suggested, and while the data to the page, it still does not pick up the styling. Is it confused because it’s a list of posts within a category, shown on a Page?
Mark says
I figured it out. It needed a bit different div and class stuff. Here is what works.
(I hope I paste this in without screwing up your comment again:
Mark says
<div class="left_wp_thumb">
<?php
the_post_thumbnail();
?>
</div>
<div class="headline_area">
<h2 class-"entry_title">
<?php
the_title();
?>
</h2>
</div>
<div class="format_text entry-content">
<?php
the_excerpt();
?>
</div>
Amy says
Hi, thank you so much for this post. I have been wanting to put thumbnails (only) in a sidebar widget so I used your example loop for creating thumbnails.
I’m experiencing a curious behavior, though. The thumbnails are linked only on the home page, but none of the posts or pages. Why would $post_image[‘output’] only output the linked markup on the home page only? Hmm…
The other pages just show unlinked thumbnails.
Thanks!
kristarella says
Amy — Ugh, yeah, I’ve noticed that when using the thumbnail code sometimes too. I’m guessing that there’s a conditional statement in the code for thumbs saying “only show the link on home and archive pages”. I don’t know if that was always the case, or just recent behaviour. If it’s causing problems, try something like:
echo '<a href="' . get_permalink() . '"><img src="' . $post_image['url'] . '" alt="' . get_the_title() . '" /></a>';
Andy says
Hi I was wondering if you could use queries to render posts grouped in the year they were posted.. Like so,
2010
Post Title
Post Title
2009
Post Title
Post Title
Have been looking everywhere for some help for this seemingly simple function, was wondering if you knew how to, without using plugins..
Cheers!
kristarella says
Andy — I started to look for a solution for you and then I got distracted by work…
In theory it wouldn’t be too hard to do what you need; the main problem I’m finding with it is that there is no function built into WordPress to help us figure out which years have posts in them. So, I had to get the first and lasts posts from the blog, get their years and go from there…
Hook that function to where you want it and it should work, with a bit of styling to make it pretty.
Andy says
Hey Kristarella, thanks for your efforts! ill give it a go this afternoon! im practically useless at php but a snippet like this will get me going for now! Thanks again!
Dan Harrington says
Hi Kristarella,
I have a static homepage where I’d like to display a list of recent posts underneath my content. I know nothing about PHP so I’m just wondering if one of the snippets of code above would work for me? Thanks so much for your time. Here is the site I’m working on:
http://balihealer.com/
kristarella says
Dan — The example query and loop code I’ve given will work to give you the 5 most recent posts if you delete
&category_name=Featured&orderby=rand
from the query.Dan Harrington says
Hi Kristarella,
Thanks, but that doesn’t seem to work either. I think my issue may be that I’m using a custom template, so the hooks don’t work on the static page. Here is the code from my template:
<?php
/**
* Template Name: Homepage
*/
?><head>
<link rel="stylesheet" href="http://balihealer.com/wp-conte....." type="text/css" media="screen, projection" />
<link rel="stylesheet" href="http://balihealer.com/wp-conte....." type="text/css" media="screen, projection" />
<!–[if lte IE 8]><link rel="stylesheet" href="http://balihealer.com/wp-conte....." type="text/css" media="screen, projection" /><![endif]–>
<link rel="stylesheet" href="http://balihealer.com/wp-conte....." type="text/css" media="screen, projection" />
</head>
<div id="container">
<div id="page">
<div id="social-eat-pray-love">
<a href="http://www.facebook.com/group......" target="_blank">
<img src="http://www.balihealer.com/bali....." width="35" height="35" /><br />Follow us on Facebook</a></div>
<div id="social-eat-pray-love-2"><a href="http://twitter.com/Ketut_Liyer" target="_blank">
<img src="http://www.balihealer.com/bali....." width="35" height="35" /><br />Follow us on Twitter</a></div>
<?php echo thesis_nav_menu(); ?>
<?php echo thesis_header(); ?>
<div id="ketut-liyer-photo">
<object width="500" height="405"><param name="movie" value="http://www.youtube.com/v/7o_vB.....;<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/7o_vB....." type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="500" height="405"></embed></object>
</div>
<div id="content_box">
<div id="content">
<div class="content-column">
<div id="ketut-liyer">
<h1>About Ketut Liyer: A Healer in Bali</h1>
<p>In 1997, a young American filmmaker, fluent in the Indonesian language, returned to Bali to explore the world of Balinese healers.</p>
<p>Over many months, he filmed interviews with several legendary traditional healers â?? called â??Balianâ?? or â??dukunâ??. He also interviewed their patients and several experts â?? Balinese and Western â?? in order to better understand the world of Balinese medicine. His unprecedented access to these healers â?? living in their homes â?? participating in ritual events â?? allowed him to document many remarkable events and healing sessions.</p>
<p>One of the healers was Ketut Liyer, who became a major character in Elizabeth Gilbertâ??s best-seller â??Eat, Pray, Loveâ??. The footage depicts a man somewhat different than the character described in Gilbertâ??s book. In the footage, Liyer is in excellent health and at the height of his mental and spiritual powers. The interviews â?? conducted in Indonesian with English subtitles, reveals an articulate man with a steely intelligence, who can speak with great authority on the subject of Balinese healing and what is called sikala and niskala â?? the seen and unseen â?? that effect health.</p>
<p>Ketut Liyer, traditional healer, Elizabeth Gilbertâ??s healer from Eat, Pray, Love.</p>
</div>
</div></div>
<div class="sidebars">
<?php echo thesis_sidebars(); ?>
</div>
<?php echo thesis_footer_area(); ?>
</div>
</div>
</div>
Dan Harrington says
Not sure if that code will help much, I put it through the encoder but it looks a little garbled. I posted it on the Thesis forums here:
http://diythemes.com/forums/sh.....oop-API%29
Thanks so much for any suggestions. My guess is that the template file is causing the hook system to break somehow, I’ve tried about 10 different solutions to call in posts using the customfunctions.php file and none of them work. The question would be what is structured wrong in my template file?
kristarella says
Dan — Hooks are PHP functions within the page structure. If you rewrite the whole page, which is essentially what you’ve done with the page template, you will lose some or all of the hooks (you’ve probably still got sidebar hooks since you’re not rewriting those bits).
Page templates (in this form) are not really the right way to work with Thesis. Unless you really want to use a page template because it’s going to be implemented across many pages, the best way is to use custom templates. Take a look at Berchman’s tutorial on that. However, from what I can see of your page template, I see no reason why you’d need a page template in this case, I think what you want to do is:
That’s about it give or take a bit of fine tuning.
If you really want to stay with the page template thing, don’t try to hook the recent posts in, paste it in the page template.
Dan Harrington says
That explains quite a bit. Thanks so much! You are like the patron saint of WordPress.
Doug Hogan says
Hi Kristarella,
I’ve been looking for a while for a way to rotate a featured post section on my website between the latest 2 posts in a specific “podcast” category. And this article is closest answer I’ve found to the problem! But I was wondering if you could give me some insight on one last hurdle.
I only want one post to display at a time, so I’m working on driving this through an offset that calls randomly from an array of values. i.e. either 0 or 1. But I’m struggling with implementing this into the code. This is what I have so far after modding one of your suggestions above.
<?php
$post_offet = array(0,1);
foreach ($post_offset as $offsetted) {
$recent_post = new WP_Query(‘showposts=1&category_name=podcast&offset=’ . $offsetted->term_id);
while($recent_post->have_posts()) : $recent_post->the_post();
?>
What am I doing wrong here? Thanks in advance for your help!
kristarella says
Doug — Hrm, I was sure I’d done an offset one in the comments of this post, but apparently not. So, good job on getting as far as you did. It’s not working because an array is just a set of values and the foreach function goes through each value and executes the code within the foreach. So effectively you are just saying “for offset 0 this is the loop, and now for offset 1 here is the loop”.
You need something more like:
Where rand() generates a random integer between 0 and 1.
John says
Hi kristerella, i have a lot of PAGE pages on my sites – some of them are the standard About, Contact, TOS pages which I’m happy to use with the standard Thesis framework – however, for all my other Pages (and any new Page I set up in the future) I would like to change these with the following characteristics:
– No nav menu
– use 1 sidebar instead of 2
– use different widgets in this sidebar
(and maybe a couple of other changes)
As I’m not a programmer or php person I’m trying to figure out from reading sites like yours what the best way to do this is? I have the Thesis Openhook plugin on my site so thought maybe there was a way of specifying these characteristics in the thesis_hook_custom_template bit – but then as i only want these characteristics for certain pages, not sure how i could do this.
The frustrating thing for me is trying to find where the default thesis php code is – because every file i go into only shows the code “thesis_html_framework();” – which means nothing to me – this is all the index.php and custom_template.php files have, and i can’t find a page.php file anywhere – thing is, i don’t know any php in my head, but if i can see the php code on paper or copy it from the standard thesis framework then i can figure it out by looking at it and alter it to my needs – but, like i said, i can’t find this code anywhere? boo hoo!
Sorry, i think i just bombarded you with a few different questions – but would be great to get some guidance.
kristarella says
John — I’m working on a post that will address some of those issues, but overall this is probably something that needs to be worked through in the forum; it’s too big for post comments. Let me know the URL if you’ve already created a thread.
John says
Hi kristarella – i have a thread at this link:
http://diythemes.com/forums/sh.....for-Thesis
Thanks for reply – Look forward to your post
Rick A says
I am doing a website for one of the children’s ministries at my church using an Event Calendar plugin that assigns upcoming events to the Events and Future categories. I would like the home page of the website to display the event posts that are in the “future” category using Thesis “Features & Teasers” and they should be arranged by post date in ascending order.
This seems like it ought to be simple to do but, as a php newbie, it’s perplexing to me. Your help would be greatly appreciated.
kristarella says
Rick — The following should do it:
Note that ascending order is oldest first, so you might get some events that are past if the events aren’t removed from the category when they’re over.
Rick A says
It works perfectly! Thanks so much.
Becky says
Thanks for the detailed explanation. I’ve been out of the WordPress ecosystem for awhile, and this was a fabulous refresher!
I have a related question that I’m hoping you can address. Using Thesis, I’d like to create a page that uses the standard loop & pagination, but a modified query (it will select a subset of the authors). If I weren’t using Thesis, I’d simply create a copy of index.php & only change the query. What’s the equivalent method for Thesis? (I know how to construct the query, create a custom template with a function, etc… I’m really just stuck on how to change the query without changing the loop or any of its associated hooks.)
kristarella says
Becky — If you hook the first code chunk before the content it modifies the query. E.g.,
Or there’s also the new loop API in Thesis where you can make a custom template with a new loop, if you need more complicated changes than the above query structure allows.
Becky says
Kris – Thanks for your prompt reply!
I’ve literally spent all day tinkering with variations of your suggestion: both using the thesis_hook_before_content hook to override the query, and playing with the loop API (and some terrible combinations of the two). At least I know I’m on the right track. 🙂
The problem is that my custom query involves selecting multiple authors, and query_posts just doesn’t play nice in that situation. So I’ve tried $wpdb->get_results using a nice sql query. At the moment, $wpd is refusing to globalize, but earlier in the day I did get that method working. I just don’t know how to conclude that function so that the standard loop has the right data to work with (and paginates correctly, etc). I don’t want to rewrite the loop (indeed, down the road I’ll probably use the thesis hooks to shake it up a bit). I also tried using the loop API, creating a conditional that only affects this page (‘experts-2’); it tweaks the query and then feeds it right back into the default loop, which is exactly what I want, but I can’t figure out how to correctly globalize $wpdb in that scenario. Any advice is much appreciated!
$loopty_loop = new my_loops;
class my_loops extends thesis_custom_loop {
function page() {
if (is_page(‘experts-2’)) {
$my_query = "
SELECT * FROM $wpdb->posts
WHERE post_status = ‘publish’
AND (post_author = 1 OR post_author = 2)
ORDER BY post_date DESC
";
global $wpdb;
$my_results = $wpdb->get_results($my_query);
while ($my_results->have_posts()) {
global $my_results;
$my_results->the_post();
thesis_loop::archive();
}
}
else { thesis_loop::page(); }
}
}
Mary says
Hi Kristarella,
Thank you soooo much! I’m relatively new to php and thesis, so I’ve been on your site 24/7 lately since I use it as a guide..
Anyway, I want to show random posts on my sidebar and followed this exactly, but none of my thumbnails will show up. I have tried using both the thumb option in my post as well as a custom field (named it ‘thumb’) — still no go. Is there something that I’m missing?
Thank you very much in advance!
Mary
kristarella says
Mary — Since there’s no link to your site I can only guess as to what might be going wrong. Are you using Thesis? So, you tried to add the image URL to the Thesis Thumbnail field? The custom field key is “thesis_thumb”, not “thumb”, so the latter definitely wouldn’t do anything. You could try the former.
Mary says
Thank you so much for the speedy reply 🙂
I tried your suggestion and it works! I’m currently working locally so my site design with thesis is not up yet.
You rock 😀 😀 😀
kristarella says
Becky — All the examples of the direct SQL query method use a
foreach
loop rather than awhile->have_posts();
loop. Does the while loop work? I can’t get it to work. Previously I’ve created an array of post IDs from the SELECT and then usedquery_posts()
. Try this:kristarella says
Becky — WordPress messed royally with the code I pasted. I’ve corrected it now, so make sure you get it from the web page and not from any notification email!
Chenoa says
Hello Kristarella,
I am using the rotating function you wrote for Doug up above on my homepage, and I was just wondering how I can have the function rotate through all the posts in that category instead of two posts.
Is there a way to do that? And is there a way to show an arrow the user can click to show the next featured post? I basically want to show one featured post at a time, and have it automatically reload to show the next featured post, with the option of clicking back and forth between the posts.
I know there are plugins for featured post slideshows, but they all take away the styling of the posts. I want them to stay the same as far as styling.
Thank you so much!
kristarella says
Chenoa — That particular code only shows one post on the page and only changes when the page is reloaded. To rotate posts after the page has already loaded you need to have all the required posts in the HTML already and then use CSS and javascript to hide all but one post and rotate them. It’s a lot more complicated and I’d recommend trying the SlideDeck plugin; it’s really easy to make a post rotator and I don’t think it messed up formatting.
Chenoa says
Thanks for the quick response and feedback! I really appreciate it. I’ll be testing out the SlideDeck very soon. 🙂
Clarence Johnson says
Great post … thank you for sharing.
If I have a 100 images associated with a specific category, but I wanted the result page to show 50 at a time…how could I code the custom function to include the nav links in order to view the remain 50?
Thanks in advance
kristarella says
Clarence — It depends how you have written the query, but you should be able to use next_posts_link and the corresponding previous link after the loop.
Gee says
hi kristella. thank you very much for this informative post. i’m not so techie so i just i edited some of my posts just to add it to the “Featured” category and copied the code exactly so that I will not mess up with it.
anyway, is there a way to include a thumbnail with the list of posts? someone posted this pic in the thesis forum and that’s exactly what I wanted too. the question was already answered in the forum but i’m having second thoughts about copying the code because the one who posted the question kept complaining about getting error messages.
thanks!
kristarella says
Gee — The thumbnail code is in the post above. It can be combined with whichever of the other code you used.
Pierre says
Hi Kristarella
There’s a lot of “Random posts stuff” for wordpress, but “Random Comments” is a rare fish.
So far, I’m using the function below on this site HERE. But I need some enhancements.
1. getting the permalink to the “post_title” instead of “com_excerpt”.
1. finding the correct syntax to exclude some (2) categories from the output.
2. Finding a function to target the spot between my widgets where I want them to appear. (could it be done using a “shortcode” inserted in a text widget ? ) or as your exemple (USING THE CUSTOM LOOP IN THESIS : ADD IT TO THE SIDEBAR )
[PHP]function random_comments() {
global $wpdb;
if (!is_page(0)){
?>
comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = ‘1’ AND comment_type = ” AND post_password = ” ORDER BY RAND() DESC LIMIT 6″;
$recentComments .= “\n”;
$comments = $wpdb->get_results($sql);
$recentComments = $pre_HTML;
foreach ($comments as $comment) {
$recentComments .= “\n”.strip_tags($comment->comment_author) . ” : “.strip_tags($comment->post_title) . ” :” . “ID).”#comment-” . $comment->comment_ID . “\” title=\”on “.$comment->post_title . “\”>” .strip_tags($comment->com_excerpt). “_[…]”. ““; }
$recentComments .= “\n”;
$recentComments .= $post_HTML;
echo $recentComments;
?>
<?php
}
}
add_action('thesis_hook_after_sidebar_2', 'random_comments');[/PHP]
I'v tried many twiddle, but crashed the site everytime.
Thank you for any help.
Pierre
Pierre says
Oups…
function random_comments() {
global $wpdb;
if (!is_page(0)){
?>
<div id="random">
<?php
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url, SUBSTRING(comment_content,1,25) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = ‘1’ AND comment_type = ” AND post_password = ” ORDER BY RAND() DESC LIMIT 6";
$recentComments .= "\n<li>";
$comments = $wpdb->get_results($sql);
$recentComments = $pre_HTML;
foreach ($comments as $comment) {
$recentComments .= "\n<div class=rand>".strip_tags($comment->comment_author) . " : ".strip_tags($comment->post_title) . " :" . "</div><div class=randt><a href=\"" . get_permalink($comment->ID)."#comment-" . $comment->comment_ID . "\" title=\"on ".$comment->post_title . "\">" .strip_tags($comment->com_excerpt). "_[…]". "</a></div>"; }
$recentComments .= "\n</li>";
$recentComments .= $post_HTML;
echo $recentComments;
?>
</div>
<?php
}
}
add_action(‘thesis_hook_after_sidebar_2’, ‘random_comments’);
Pierre
Pierre says
Oups…again
My test site : http://pierrecote.fondationcem.org
Pierre
Johnny says
Hey!
I’ve tried your examples, and tried to rewite them to work on a category, when i’m in that category i would like to get read in some custom fields and stuff. But i simply cant get it working! Don’t know what I’m doing wrong but for sure there is something.
How would you write the code for it to work on a specific category?
kristarella says
Johnny — You need a category conditional tag. On a category archive page you’d use:
On a single post belonging to a category you’d use:
As for the rest of the code it really depends on what you’re trying to achieve and what part of the page it’s going on.
Dee says
I tried the code for linked related posts with thumbnail…and it worked on the first attempt! Love it! Thank you!
Flat shoes says
Hi Kris,
how make “thumb” size same with homepage post thumbnails. I use 150 x 150 thumbnail on homepage. and where I can put Related Post in the code. I have tried but always getting error.
thank you
kristarella says
Flat shoes — Your thumbnail size should be the same already. You would have to show me your code and the associated error for me to help any further, because I know there’s no errors in my code above, so it must be the way you’re trying to use it.
Dave says
Really helpful, and really easy to follow. Thanks!
Pretty Shiny Sparkly says
I’m having a little trouble with implementing something I
had that worked wonderfully on my previous theme, but now I’m on
Thesis and trying to figure out this whole hook & filter
thing. Help! 🙂 Basically my story all lies here on this forum
post:
http://diythemes.com/forums/sh.....post197136
And this is what I’ve come up with, which is non-functional (and
I’m not surprised, since I know zip about this stuff):
add_theme_support(‘post-thumbnails’); set_post_thumbnail_size(
9999, 150 ); function custom_wp_thumb() { the_post_thumbnail(); }
add_action(‘thesis_hook_before_teaser’,’custom_wp_thumb’); function
custom_outfit_posts() { if ( is_category(‘Outfits’) ) :
$custom_loop = new
WP_Query(‘showposts=-1&category_name=Outfits’); if (
$custom_loop->have_posts() ) : echo
‘Outfit Posts‘; echo
‘
‘; while- ‘ .
( $custom_loop->have_posts() ) :
$custom_loop->the_post(); $post_image =
thesis_post_image_info(‘thumb’); echo ‘
$post_image[‘output’] . ‘
‘; endwhile;
wp_reset_query(); echo ‘
‘; endif; endif; }
remove_action(‘thesis_hook_archives_template’,
‘thesis_archives_template’);
add_action(‘thesis_hook_archives_template’, ‘custom_outfit_posts’);
I’m looking for a way to display *just* the category Outfits as
small thumbnails (no text, nothing but a linked thumbnail)
horizontally (float left). You can see how I implented this
previously (non-Thesis) in the forum post I linked to. I would so
very much–no, GREATLY–appreciate any insight you can provide.
Thanks Kristarella! ? Kristina, Pretty Shiny
Sparkly
Gustavo @ GizmosHub says
I have the similar posts plugin and I’m trying to show them after the post box. How would I be able to do that?
kristarella says
Kristina — How are you going with this category loop issue. I took a look on the forum and there was progress, but I’m not sure if it was finalised. I’m sure I can help you if you need more help with it.
Gustavo — The plugin probably has a function for you to insert into your template (check the plugin documentation), you would add it with a function in custom_functions.php. E.g.,
Mike says
Hey
You’re a pro! Every time I read this post, you teach me something new.
Could you help me figure something out?
I’m trying to implement a span with number of comments and a commentbubble.gif right after the post title in the sidebar using your “Add it to the sidebar” code.
function widget_popular_posts() {
$custom_loop = new WP_Query(‘showposts=5&orderby=comment_count&order=DESC’);
if ( $custom_loop->have_posts() ) :
echo ‘<li class="widget popular_posts">’;
echo ‘<h3>Popular Posts</h3>’;
echo ‘<ul>’;
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
echo ‘<li><a href="’ . get_permalink() . ‘">’ . get_the_title() . ‘</a></li>’;
endwhile;
wp_reset_query();
echo ‘</ul>’;
echo ‘</li>’;
endif;
}
add_action(‘thesis_hook_after_sidebar_1′,’widget_popular_posts’);
This code is the one I’d like to implement to show the comment number and bubble.
<?php comments_number(__(‘<img src="http://www.dingoh.com/wp-conte.....t;> 0 comments’, ‘thesis’), __(‘<img src="http://www.dingoh.com/wp-conte.....t;> 1 comment’, ‘thesis’), __(‘<img src="http://www.dingoh.com/wp-conte.....t;> % comments’, ‘thesis’)); ?>
Once again, thank you for the great tutorial.
Best,
Mike
Mike says
Nevermind! I figured it out.
For those of you interested, here’s the code:
function widget_popular_posts() {
$custom_loop = new WP_Query(‘showposts=5&orderby=comment_count&order=DESC’);
if ( $custom_loop->have_posts() ) :
echo ‘<li class="widget popular_posts">’;
echo ‘<h3>Popular Posts</h3>’;
echo ‘<ul>’;
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
$post_image = thesis_post_image_info(‘thumb’);
echo ‘<li>’ . $post_image[‘output’] . ‘<a href="’ . get_permalink() . ‘"> ‘ . get_the_title() . ‘ <span><img src="YOUR COMMENT BUBBLE URL"/>’ . get_comments_number() . ‘</span></a></li>’;
endwhile;
wp_reset_query();
echo ‘</ul>’;
echo ‘</li>’;
endif;
}
add_action(‘thesis_hook_after_sidebar_1′,’widget_popular_posts’);
If you want to style the number to be a different color/font-weight use:
.custom li.popular_posts span {}
Cheers,
Mike
kristarella says
Mike — Good on you, and thanks for sharing!
JC says
Hello, I was referred here after asking a question on the thesis forum.
http://diythemes.com/forums/sh.....post207493
Basically i’m wanting to remove the content area of the is_front_page without doing something silly like .custom #content_area {display: none;}
Not really sure where to get started on a custom loop.
thanks!
kristarella says
JC — I don’t think you can just remove the whole content_area, markup and all, via a filter or loop, but you can use the filters in my squeeze page post to remove the sidebars and then you can use a custom loop with the Thesis loop API to remove the page contents. E.g.,
That should result in no sidebars and no font page contents, but the divs for
#content_area
and#content
will still be there, containing nothing.JC says
thanks so much for this. However, I just went ahead and scrapped the way I had the home page set up and just created a custom template. http://www.jcdfitness.com – that’s how it turned out.
takis says
Hi @Kristarella,
how about having random posts over multiple pages?
I’ve been looking for an answer a month now, and I still haven`t got it to work.
I`m building a gallery with custom posts and with the “orderby=rand” argument alone, there is no guarantee that subsequent pages won’t repeat posts, as it re-randomizes each page without taking into account what’s already been displayed.
Any ideas on that?
kristarella says
Takis — How are you doing the pagination? Are you using posts_per_page in the query?
ben says
I looked for a long time for a well-written article on this, thank you so much! I’m a wp newbie from the design side of things, and I just couldn’t understand some other explanations. You have a very clear way of writing that makes sense. Thanks again!
takis says
Some of the ways i`ve tried:
*
$paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
$args = array(‘post_type’ => ‘gallery’, ‘paged’=>$paged, ‘posts_per_page’ => 60, ‘orderby’=>rand);
query_posts($args);
**
1. Get output of MyLoopCode() as an array.
2. Shuffle the array.
3. Display contents.
Found here: http://stackoverflow.com/quest.....press-loop
***
Now trying an ajaxified way but neither this seems to work for now.
—-
I tried a js way of loading all posts as an array, randomise them and then split them in pages but, there are about 700 posts with thumbs to be split in pages of 60. The page is huge and loads really slow.
—
Do you think maybe the wppagenavi plugin is to blame?
—
That`s all I have for now. Any ideas?
dave says
i’ve been trying to figure out how to make a custom loop for my sidebar that displays other posts in the same category but EXCLUDES the current single post. as it stands, this displays a list of post titles and excerpts in the same category, but it INCLUDES the current single post in the list. this seems like it should be a simple fix but i’m in over my head php-wise! any ideas??
<?php
$query = "showposts=10&orderby=date&cat=";
foreach [ref]get_the_category([/ref] as $category) {
$query .= $category->cat_ID .",";
}
query_posts($query);
?>
<ul>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title() ?></a>
<?php the_excerpt(); ?>
</li>
<?php endwhile; ?>
</ul>
thanks!
Alwin says
how can i put random adsense location between thesis teaser
Janne says
Hi,
I really love your tutorials, but still have an unpleasant problem, hope you van help me or at least give a hint what I doing wrong.
I would like to show resent posts with thumbnails in sidebar (using Thesis), I tried to use your loop How about using thumbnails instead of post titles but it did work 🙁
Any advice?
kristarella says
Janne — Without knowing more I can’t really help. If I could see the code or the page that it’s supposed to appear on I might be able to say more.
kristarella says
Alwin — You can add adverts between certain teasers like so:
Just change the number 1 to whichever number you need (an odd number, since there’s two teasers in each teasers_box).
As for them being random ads… there’s several ways to do it, mostly PHP related and not Thesis specific.
kristarella says
Takis — I would have thought that the first option you listed should work. If that’s not working it’s possible that WP Page Navi is to blame. What if you use the regular previous/next WP links?
kristarella says
Dave — Try this loop, which fetches the current post’s ID, excludes it from the loop and gets the category for that post too.
I’ve used mostly the same code that you had, but really you should use
new WP_Query
as demonstrated in the post, rather thanquery_posts
, which is for the main loop on the page.SeanE says
Nice custom loop post and thank you.
So riddle me this bat woman ; )
I have teasers on the homepage of a site and want to display only teasers of posts from a certain category. Using below, blows up “teaser” boxes, formatting etc. but does only show from correct categories. How can I adapt this to essentially tell WOrdpress through thesis ? to…
IF is home page,
SHOW only teasers from posts in the “homepage” category (while retaining all formatting and selections associated with teasers).
function limit_front_page() {
global $query_string;
if (is_home()) {
query_posts($query_string.’cat=2,6′);
}
}
add_action(‘thesis_hook_before_content’, ‘limit_front_page’);
_______________________
grazie.
Sean
kristarella says
Sean — You’re missing an ampersand in the query. This should work:
query_posts($query_string.'&cat=2,6');
SeanE says
Ahhh. Could not get that to work. So I am stuck.
I now have a function that adequately restricts categories of teasers on home page. Unfortunately, the page also generates teasers via Thesis (which of course, I cannot figure out how to limit to a specific category). So I get one set of unfiltered feature results via thesis and one set of filtered results via the function.
you can see it here http://www.lppc.org/eewg/
and here is the current function:
/* BEGIN TEASER BOX HOMEPAGE CAT ONLY */
function teaser_box_code() {
if(is_home()) {
$my_query = new WP_Query(‘posts_per_page=10&cat=8’); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID;
echo ‘<div class="teasers_box">’;
thesis_teaser(‘teaser’, $post_count = false, $right = false);
echo ‘</div>’;
endwhile;
} }
add_action(‘thesis_hook_after_content’, ‘teaser_box_code’);
/* END TEASER BOX post */
Am I missing something fundamental here?
kristarella says
Seane — I don’t know why your previous function wouldn’t work if you added the ampersand into the correct place (N.B., I only corrected the part that was wrong, the rest of the function was fine and still needed).
If you want to create a whole new query & loop to replace the default one, use the Thesis Custom Loop API, rather than hooking before or after the content.
SeanE says
thank you. With the ampersand, the previous function does work in terms of limiting list of posts to specific category on the page, but it does not apply to teasers on the home page (and I’m not sure why or how to limit teasers to a specific category).
kristarella says
SeanE — it should work with the teasers… Can you paste your functions file in pastebin.com for me; perhaps I can find the problem?
kristarella says
SeanE — The following will cause posts from category 5 to show on the home page without turning it into an archive-like page:
SeanE says
OMG, I knew there was a simple way to do it without a custom API. How can I say thank you? I have been trying to figure this out and asking for help at DIYthemes for several days. Any repercussions to that approach btw? You are essentially hard setting category on the home page, right?
SeanE
SeanE says
ooops. Spoke to soon on this one. SO that filter kills the main menu navigation (I assume because if cat=8 and nothing else, then wordpress cannot generate paged navigation?).
kristarella says
SeanE — What do you mean by main menu navigation? Pagination works fine in my test.
SeanE says
If I use the function below, my wordpress menu disappears (this main menu is generated by WP, not thesis). To test that it was not a conflict with another function, I cleared custom_functions of all code with the exception of the one function, and it still drops out the WP menu.
function myFilter($query) {
if ($query->is_home) {
$query->set(‘cat’,’8′);
}
return $query;
}
add_filter(‘pre_get_posts’,’myFilter’);
kristarella says
SeanE — Try this function instead:
I don’t know why, but it seems to fix it… I found it in a forum.
shames says
i dunno how to this but this in thesis, what i want is only to show all todays post in my home, and in the archive/category will show only 1 post in each category.
this is what I’m using in normal theme
foreach(get_the_category() as $category)
{
$cat = $category->cat_ID;
}
$today = getdate();
query_posts(‘year=’ .$today[“year”] .’&monthnum=’ .$today[“mon”] .’&day=’ .$today[“mday”]. ‘orderby=menu_order&cat=’ . $cat . ‘&posts_per_page=1’ );
}
maybe you could help me out here.. thanks
shames says
function today_post () {
if (is_home()) {
$today = getdate();
query_posts(‘year=’ .$today[“year”] .’&monthnum=’ .$today[“mon”] .’&day=’ .$today[“mday”].’&order=ASC’ );
}
}
add_filter(‘thesis_hook_before_content’,’today_post’);
manage to get this working in my homepage, but the problem it only shows the post titles without the teaser/content
shames says
never mind i fix that. i successfully managed to show my homepage only todays post. 😀
my 2nd problem is i want only to show 1 post in each category.
SeanE says
That did it, thank you Kristarella. BTW, I checked out your profile, my birthday is April 10th also! : )
I sent a little thanks via Paypal over the weekend.
Cheerio.
Sean
Ayesha Khan says
HI KRISTARELLA, is there any way to show the summary of only first one or two posts while displaying recent posts from any specific category with thumbnail? as posts displayed in first colunm of this site http://wpmu.org/
I could not find any help from google. I think nobody telling how to do it. Or may be it is little complicated. Don’t know if it is possible in thesis or not.. What you say? If you can tell me how to do it then i will be very Thankful to you. 😉
kristarella says
Ayesha — Do you have access to the DIYthemes forums? I’m pretty sure we’ve discussed custom teaser loops over there.
Ayesha Khan says
No, i dont have access to DIYthemes forums, is there any other online resource to learn how to do it?
kristarella says
Ayesha — I think I misread your initial comment: I thought you meant making teasers from a particular category, but just titles and images is pretty easy…
Pretty much all the information you need is already in the post. Use the first code snippet in thesis_hook_before_content and use the is_home() conditional code to limit it to the home page, but change the
&cat=-5
to&posts_per_page=2
to limit the large posts to 2 without affecting the number of posts on archive pages.Then you can use a combination of the “add it to the sidebar” and the function after that to add post titles with thumbnails. Just change the hook you add it to to thesis_hook_after_content instead of the sidebar.
Rachel says
I would like to create a portfolio page with just thumbnails on the page. I’d also like to put some random thumbnails on my homepage to give a glimpse as to what is in the portfolio page. Can you help me with this? I was trying to implement your code, but not having much luck getting it to display correctly.
Also, I don’t want this portfolio category to display with my regular blog posts.
Rachel
kristarella says
Rachel — Are you using Thesis? Are you using Post Images with Thesis on your portfolio posts? If so you should be able to use the thesis thumbs function and insert it onto a page with
thesis_hook_after_post
rather than than hooking it into the sidebar. Change the number of posts and category name and it should be a reasonable start. You’ll probably need some info from the links at the end of the post as well.MPE says
Thank you so much..i love this tutorial… 😀
Leanne says
I have been searching all afternoon to find a way to show related posts at the bottom of a single page post as thumbnails. There are a few solutions out there but none that deal with the situation of a post being assigned to more than 1 category.
The php and css on DIY Themes works (without thumbs) but lists mutliple categories which is very ugly!
Other php and css I have found for related posts with thumbnails at the post crash my database – maybe because of the multiple category thing? – and I have had to get into my FTP client to remove the code and regain access to wordpress admin.
I would dearly love some help on how to deal with this and any suggestions would be GREATLY APPRECIATED 🙂
Thanks in advance, Leanne
Leanne says
****Sorry! That above comment should read “…Other php and css I have found for related posts with thumbnails at the end of a single page post crash my database..”***
kristarella says
Leanne — Generally it shouldn’t matter if you have multiple categories to your posts, but I guess you might need to only choose one category to find the related posts otherwise the code would either be rather convoluted, or you might be returning multiple categories when the code expects one, so you’d need to account for that.
I wrote this a while ago, but glancing over the related posts loop it looks like it only uses the first category from the post, so multiple categories won’t break it. Also you could probably just delete all the category related lines and only use tags to find related posts.
Otherwise there are plugins that you could try, rather than custom code.
Peter says
just awesome!
Robert Schrader says
Dumb question, but how do I add the category name at the top of a div that contains posts from a specific category?
i.e. (this is really low tech sorry)
______________________________________________
CATEGORY NAME
[post img][post img][post img][post img][post img]
excerpt excerpt excerpt excerpt excerpt
_____________________________________________
kristarella says
Robert — it kind of depends how you’re fetching the posts and which page you’re on… You can use single_cat_title(); on a category archive page, or you can use get_cat_name() if you’ve got the category ID (e.g., if you used the ID in WP_Query). Try the WordPress template tags and functions list to see which is right for you.
Robert Schrader says
Where in the function do I place that query? Again I’m not sure if I was clear but I want it to be a label, particularly one I can style with CSS. Alternatively, is it possible to insert a plain text title within one of these PHP functions?
kristarella says
Robert — In answer to the second question, yes, most of these functions output plain text. So, I guess then in order to style it with CSS you will need to wrap it in HTML, like a heading tag, or a paragraph with a class, or something like that.
To give you anymore specific information I would need to know more about the loop you are already using (and if you haven’t started writing it yet, I would recommend doing that before moving ahead because it’s easier to figure out what is going on once you’re outputting code). There’s at least 5 code examples in the post above, and you haven’t said if you’re using one of those or if you’re editing a theme template file, or what theme you’re using… The right code depends on all of those things.
Robert Schrader says
Hi Krista:
I am attempted to place a custom loop in my custom_functions.php file (I spliced together a couple you’d made) as follows, as nothing appears on my homepage. What am I doing wrong?
function custom_inspiration_posts() {
if ( is_home() ) :
$custom_loop = new WP_Query(‘showposts=5&category_name=Inspiration&orderby=rand’);
if ( $custom_loop->have_posts() ) :
echo ‘Get Inspired‘;
echo ”;
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
$post_image = thesis_post_image_info(‘image’);
echo ” . $post_image[‘output’] . ”;
echo ‘‘ . get_the_title() . ‘‘;
endwhile;
wp_reset_query();
echo ”;
endif;
endif;
}
add_action(‘thesis_hook_before_content’,’custom_inspiration_posts’);
Robert Schrader says
D’oh. I forgot to encode the code. Here it is:
function custom_inspiration_posts() {
if ( is_home() ) :
$custom_loop = new WP_Query(‘showposts=5&category_name=Inspiration&orderby=rand’);
if ( $custom_loop->have_posts() ) :
echo ‘<strong>Get Inspired</strong>’;
echo ‘<ul class="inspiration">’;
while ( $custom_loop->have_posts() ) : $custom_loop->the_post();
$post_image = thesis_post_image_info(‘image’);
echo ‘<li>’ . $post_image[‘output’] . ‘</li>’;
echo ‘<li><a href="’ . get_permalink() . ‘">’ . get_the_title() . ‘</a></li>’;
endwhile;
wp_reset_query();
echo ‘</ul>’;
endif;
endif;
}
add_action(‘thesis_hook_before_content’,’custom_inspiration_posts’);
kristarella says
Robert — I tested your code and it works: I changed the category name to Uncategorized to test it on my test site and it was fine. Nothing will show up if there’s nothing in your Inspiration category yet. I made a slight change so that the post image list item only shows when there is a post image:
As far as getting the category name with PHP goes. I would replace the Get Inspired line with
echo '<h2>' . get_cat_name(ID) . '</h2>';
, so you can target the style of it with h2 and the get_cat_name() function fetches the category name according to the ID, but in your example there is no point getting the category name via PHP because you are using the name in your query, and you are not cycling through multiple categories, so it is a waste of a database call to use PHP to display the category name in that case.Jeric says
Hello kristarella,
Good day and thanks for this post of yours, I’m a newbie in the web development world and this site of yours is a big help for me. I’m not so sure if this loop thing is the solution I’m looking for. I created a content within the thesis hook thesis_before_post_box but what I wanted is to make it appear only in the homepage of my site. I found out that it’s showing in all other post and pages in my site which is not good. Can you please help me out? I have been searching the web for like days now but I can’t find a solution. I’m just hoping that you have the answer to my problem. Would appreciate very much your help. Thanks and more power
Sincerely,
Jerico