If you want to apply the required
attribute every time you use wp_categories_dropdown
, use wp_dropdown_cats
filter as suggested in other answers:
add_filter( 'wp_dropdown_cats', 'wp_dropdown_categories_required' );
function wp_dropdown_categories_required( $output ){
return preg_replace(
'^' . preg_quote( '<select ' ) . '^',
'<select required ',
$output
);
}
If you want to apply the required
attribute only in especific situations, you can use wp_dropdown_categories
with echo
argument set to false
, introduce the required
attribute in the returned string and then echo
:
$args = array(
'show_option_none' => __( 'Select one', 'text-domain' ),
'taxonomy' => 'my_tax',
'id' => 'tax-type',
'echo' => false,
);
$cat_dropdown = wp_dropdown_categories( $args );
$cat_dropdown = preg_replace(
'^' . preg_quote( '<select ' ) . '^',
'<select required ',
$cat_dropdown
);
echo $cat_dropdown;
Or maybe better, apply the filter combined with a custom required
attribute:
add_filter( 'wp_dropdown_cats', 'wp_dropdown_categories_required', 10, 2 );
function wp_dropdown_categories_required( $output, $args ){
if( isset( $args['required'] ) && $args['required'] ) {
$output = preg_replace(
'^' . preg_quote( '<select ' ) . '^',
'<select required ',
$output
);
}
return $output;
}
And then use wp_dropdown_categories
like this:
$args = array(
'show_option_none' => __( 'Select one', 'text-domain' ),
'taxonomy' => 'my_tax',
'id' => 'tax-type',
'required' => true,
);
wp_dropdown_categories( $args );
About the second question, you should know that there is a "one question per thread" rule. Remember that for future questions. Than being said, -1
is the default value for option_none_value
argument. This argument was not documented (now it is, I've added it to codex). You can override it as follow:
$args = array(
'show_option_none' => __( 'Select one', 'text-domain' ),
'option_none_value' => NULL,
'taxonomy' => 'my_tax',
'id' => 'tax-type',
'echo' => false
);
PD: I'm not sure if NULL
is a valid value for a option
in a select
element. Also, note that ''
(empty string) is not the same that NULL
. An empty string is a string data type with zero length; NULL
is not any date type and has not data properties, it is nothing.