Own query posts widget, category selection
-
Hello,
I’m trying to create my own query posts widget in which I will, among other things, be able to choose what categories to query posts from.
In the “Query Posts Plugin” you enter the category number(s) in a textfield, and it worked great. I’ve managed to make my own with only that part right now, but you don’t always know the numbers.
It’d be better to allow the person to select one or multiple in a select list. Since I’m quite new to widgets, and not a very experienced PHP programmer at all, I’m stuck.This is what I got now, it let’s you enter a category number and it’ll query the posts from it:
class OwnQuery extends WP_Widget { function OwnQuery() { // widget actual processes parent::WP_Widget(false, $name = 'OwnQuery'); } function form($instance) { $category = esc_attr($instance['category']); ?> <p>Categories:<br /> <?php $category_ids = get_all_category_ids(); foreach($category_ids as $cat_id) { $cat_name = get_cat_name($cat_id); echo $cat_id . ': ' . $cat_name . '<br />'; } ?> </p> <p><label for="<?php echo $this->get_field_id('category'); ?>"><?php _e('category:'); ?> <input class="widefat" id="<?php echo $this->get_field_id('category'); ?>" name="<?php echo $this->get_field_name('category'); ?>" type="text" value="<?php echo $category; ?>" /></label></p> <?php } function update($new_instance, $old_instance) { // processes widget options to be saved $instance = $old_instance; $instance['category'] = strip_tags($new_instance['category']); return $instance; } function widget($args, $instance) { // outputs the content of the widget extract( $args ); $category = apply_filters('widget_title', $instance['category']); ?> <?php echo $before_widget; ?> <?php if ( $category ) ?> <?php // Start your custom WP_query $my_query = new WP_query(); $args = array( 'cat' => $category ); // Assign predefined $args to your query $my_query->query($args); // Run your normal loop if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); // do loop stuff echo the_title(); echo the_content(); echo "<hr />"; endwhile; else : echo "no posts"; endif; // RESET THE QUERY wp_reset_query(); ?> <?php echo $after_widget; ?> <?php } } add_action('widgets_init', create_function('', 'return register_widget("OwnQuery");'));
I’ve tried out different things with dropdown lists etc, but I’ve only failed.
Anyone got an idea, or anyone made their own that would work?Thanks
- The topic ‘Own query posts widget, category selection’ is closed to new replies.