So, I had a request to customize the recent posts widget on a WordPress site that I do work for. Basically, the site has two authors, each with their own section, but the recent posts widget was showing posts from both authors, instead of only from one.
I thought customizing the widget would be a simple manner of adding something in the widget logic space available in the wp admin back end, but it turned out to be a bit more involved. To start with, I had to get the PHP code widget plugin which let’s you insert php code into a widget (I could manually add the code on the sidebar.php file, but this seemed more customizable). Then I placed the following in the widget:
<ul> <?php $recentPosts = new WP_Query(); $recentPosts->query('showposts=5&author=4'); // add whatever parameters you want here ?> <?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?> <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul>
This code worked fine, but I also only wanted to display this recent posts widget on a certain page (ie the authors). I have the author page on an actual page in the site, so I thought it would be a simple matter of adding is_page() to the widget logic, but that wasn’t working. It frustrated me a bit until I found out what the problem was.
Basically, even though wordpress was on a page.php template, it wasn’t viewed that way. Instead the page was being viewed as a category, and archive, because I had inserted some category loops into the page.php template. To see how wordpress views a page, whether as is_home, is_category, is_search, is_page and so on, I was directed to a very helpful plugin called Askapache what is this.
The Askapache plugin shows how wordpress views the page and explained why the is_page() wasn’t working in the widget logic. The solution to this was to put the following:
<?php wp_reset_query(); ?>
Before the recent posts query began. I tried pasting the wp_reset_query directly above the recent posts query in the widget but that didn’t work. It did however work when I pasted the wp_reset_query at the bottom of the page.php template in question.
Anyway, it was just interesting for me to see that wordpress doesn’t always view a Page.php file as a Page, which is something I never knew before.