Widget instance options not showing correctly
-
16-10-2019 - |
Question
i have a setup like
function form($instance) {
$defaults = array(
'title' => 'Recent Products',
'number_products' => 3
);
$instance = wp_parse_args($instance, $defaults);
but my title is ok but number_products always does not show. i debuged in netbeans and found that form() is run 2 times and 1st time, variables look like
$instance = array(0)
// after wp_parse_args,
$instance = array('title' => 'Recent Products', 'number_products' => 3);
on 2nd run of wp_parse_args
, i dont know why it runs the 2nd time,
$instance = array('title' => 'Recent Products', 'number_products' => null);
// after wp_parse_args
$instance = array('title' => 'Recent Products', 'number_products' => null);
i dont really know whats happening ... can some1 enlighten me?
Solution
i finally found the answer, its actually not a problem with the code i posted. its in the update()
function. i have some validation code
function update($new_instance, $old_instance) {
$instance['title'] = esc_attr(strip_tags($new_instance['title']));
if (is_int($new_instance['number_products'])) {
if ($new_instance['number_products'] > 0)
$instance['number_products'] = $new_instance['number_products'];
else
$instance['number_products'] = 1;
} else {
$instance['number_products'] = $old_instance['number_product'];
}
return $instance;
}
the problem is at 2 places. i should be using is_numeric
over is_int
, the reason is
To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().
then, in the else, $old_instance['number_product']
should have be plural $old_instance['number_products']
OTHER TIPS
I am not sure about two runs either. Had you tried just dumping content inside function instead of debug? Something like this:
function form( $instance ) {
var_dump( $instance );
$defaults = array(
'title' => 'Recent Products',
'number_products' => 3
);
$instance = wp_parse_args($instance, $defaults);
var_dump( $instance );