Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Custom Widget with category select WordPress

  • SOLVED

Hi Everyone,

we need a custom widget, which will work as follows:

In the backend: The widget should list all categories in a custom taxonomy and save the value selected.

The output: We will use the widget to execute a shortcode with the category name as argument, so the widget should only output echo do_shortcode('[someshottcode category=<strong>(this should be the slug of the category)</strong>]');

What for (just for your information)?
We are using wp-views (www.wp-types.com) on our site and want to be able to allow users to call a specific specific view and pass a category as an argument.

Answers (1)

2012-09-16

Dbranes answers:

Hi, here is a Custom-Category widget that will give you a dropdown box for all the terms in the 'category' taxonomy
(you can just change 'category' to your custom taxonomy).


/**
* Custom Category Widget Class
*/
class custom_category_widget extends WP_Widget {

/** constructor */
function __construct() {
parent::__construct(
'my_custom_category_widget', // Base ID
'Custom Category', // Name
array( 'description' => 'Custom Category', ) // Args
);
}

/** WP_Widget::update */
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['my_custom_cat'] = strip_tags($new_instance['my_custom_cat']);
return $instance;
}

/** WP_Widget::form */
function form($instance) {

// get all terms from taxonomy 'category'
$categories = get_terms( 'category', 'orderby=count&hide_empty=0' );

//get saved cat
$current_cat=get_option("my_custom_cat");

echo "<select name=". $this->get_field_name('my_custom_cat').">";
foreach($categories as $cat){
$selected= $current_cat==$cat->slug?' selected="selected"' : '';
echo "<option value='".$cat->slug."' ".$selected.">".$cat->name."</option>";
}
echo "</select>";

//save current cat
update_option("my_custom_cat",esc_attr($instance['my_custom_cat']));
}
}
add_action('widgets_init', create_function('', 'return register_widget("custom_category_widget");'));


it saves the value into the option "my_custom_cat".

You can then access the value with the code

get_option("my_custom_cat");


You can then define a shortcode like this:

//[my_custom_cat]
function my_custom_cat_func( $atts ){

$cat= get_option("my_custom_cat");

//
// your custom code here
//
return $cat;
}
add_shortcode( 'my_custom_cat', 'my_custom_cat_func' );


to handle the selected custom category from the widget.

Hope this helps.


Yavor Trampov comments:

WOW, thanks a lot.

Yet, I will need to have this save the value separately for each instance of the widget. Right now it uses the same variable and thus always returns the value, which was chosen last. I need this to work with multiple instances.


Dbranes comments:

ok, I guess this is more like it, where you want to execute a custom shortcode
( I removed the get_option code)

/**
* Custom Category Widget Class
*/
class custom_category_widget extends WP_Widget {

/** constructor */
function __construct() {
parent::__construct(
'my_custom_category_widget', // Base ID
'Custom Category', // Name
array( 'description' => 'Custom Category', ) // Args
);
}
/**
* Front-end display of widget.
*
* @see WP_Widget::widget()
*
* @param array $args Widget arguments.
* @param array $instance Saved values from database.
*/
public function widget( $args, $instance ) {
extract( $args );

echo $before_widget;
if ( ! empty( $title ) )
echo $before_title . $title . $after_title;

// run your shortcode here:
echo do_shortcode('[someshortcode category='.$instance["my_custom_cat"].']');
//debug:
//echo "[someshortcode category='".$instance["my_custom_cat"]."']";

echo $after_widget;
}
/** @see WP_Widget::update */
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['my_custom_cat'] = strip_tags($new_instance['my_custom_cat']);
return $instance;
}

/** @see WP_Widget::form */
function form($instance) {

$categories = get_terms( 'category', 'orderby=count&hide_empty=0' );
$current_cat=esc_attr($instance['my_custom_cat'])

echo "<select name=". $this->get_field_name('my_custom_cat').">";
foreach($categories as $cat){
$selected= $current_cat==$cat->slug?' selected="selected"' : '';
echo "<option value='".$cat->slug."' ".$selected.">".$cat->name."</option>";
}
echo "</select>";
?>


<?php
}

}


Yavor Trampov comments:

This gives an error on my install:

Parse error: syntax error, unexpected T_ECHO in /Volumes/ahorn-design work/Plaut/0001PL_WebsitePlaut/WebDev/wp-content/themes/plaut/inc/site_widgets.php on line 148

(this is this line from your code: echo "<select name=". $this->get_field_name('my_custom_cat').">";


Dbranes comments:

aha, there is a missing ";"

change:

$current_cat=esc_attr($instance['my_custom_cat'])

to

$current_cat=esc_attr($instance['my_custom_cat']);


Dbranes comments:

ps: and don't forget

add_action('widgets_init', create_function('', 'return register_widget("custom_category_widget");'));


;-)


Yavor Trampov comments:

Great, this WORKS!

I need to run a couple of tests to make sure that it is fully compatible with WPML, but I don't expect to have problems there (thought about it in advance, just need to douplecheck). I will try to test by the end of the day so I can mark the question answered.

In the meantime - if you feel like writing some custom walkers, I also posted a question about this :)

Thanks again,