I’m using the following widget to retrieve a list of the custom post type jobs:
class FeaturedJobsWidget extends WP_Widget
{
function FeaturedJobsWidget()
{
$widget_ops = array('classname' => 'FeaturedJobsWidget', 'description' => 'Displays a random post with thumbnail' );
$this->WP_Widget('FeaturedJobsWidget', 'Featured Jobs', $widget_ops);
}
function form($instance)
{
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = $instance['title'];
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
return $instance;
}
function widget($args, $instance)
{
extract($args, EXTR_SKIP);
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
if (!empty($title))
echo $before_title . $title . $after_title;;
// WIDGET CODE GOES HERE
?>
<ul class="featured-jobs">
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=jobs&posts_per_page=8');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<li class="see-all-positions"><a href="http://www.pixelmatic.com/open-jobs/">See All Positions >></a></li>
</ul>
<?php
echo $after_widget;
}
}
The problem is that this part:
<?php // Create and run custom loop
$custom_posts = new WP_Query();
$custom_posts->query('post_type=jobs&posts_per_page=8');
while ($custom_posts->have_posts()) : $custom_posts->the_post();
?>
Seem to break other widgets (not sure if it is a bad practice to use WP_Query
in a widget).
Is there any other way of displaying a list of custom post types in a widget?
Use wp_reset_postdata() function after while loop to reset custom wp_query as shown in following code so that it will not break other wordpress loop.
For more information visit this page.
It’s not clear what you mean by break other widgets, but you could try to add
after your while loop to restore the global
$post
variable, or try this insteadto see if that makes any difference.