Use PHP and WP_Query in a text widget

March 10, 2012 in Blog

There are times that we would love to use little loop tricks like WP_Query in a text widget. Why? Because it teases us with it’s HTML, we can put all the markup we want in a widget but we can’t make it DO anything without FTP’ing in and creating more than we need to.

Here’s an easy way to make your WordPress 3.3.1 install recognize PHP tags in the text widget. If you add this function you can make your own widgets to hit a single category, or do whatever you want that PHP to do for you.

 

First step, open your theme’s functions.php file
step two: add this short function:

add_filter(‘widget_text’,'execute_php’,100);
function execute_php($html){
if(strpos($html,”<”.”?php”)!==false){
ob_start();
eval(“?”.”>”.$html);
$html=ob_get_contents();
ob_end_clean();
}
return $html;
}

Step three, create away. Here’s an example of a widget that grabs the latest 3 posts from post category 7 and adds appropriate styles to it.

You are not limited to this type of use, you can do anything you want that PHP can do..

The widget example:

 

<?php $custom_query = new WP_Query(‘cat=7&posts_per_page=3′); // get news cat
while($custom_query->have_posts()) : $custom_query->the_post(); ?>

<div <?php post_class(); ?> id=”post-<?php the_ID(); ?>”>
<a style=”font-size:1.2em;” href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></br>
<?php $varTitle = get_the_excerpt(”,”,false); ?>
<?php echo substr($varTitle,0,75).”…..”; ?></br>
<a class=”read-more-align-right” style=”padding-right: 3px; font-family: Georgia; font-style:italic;” href=”<?php the_permalink(); ?>”>Read more → </a></br>
<h3 class=”widgettitle”></h3>
</div>

<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>