I've found a code snippet to display the categories in a dropdown menu. It works fine but when I turn on the define('WP_DEBUG', true);
, Wordpress shows the above mentioned warning. I've just started with php and cannot figure out how to fix this warning. Could anyone help me out on this one and tell me why am I getting this message?
<?php
function replace_id_for_slug($option){
$categories = get_categories("hide_empty=0");
preg_match('/value="(\d*)"/', $option[0], $matches);
$id = $matches[1]; //problem on this line!
$slug = "";
foreach($categories as $category){
if($category->cat_ID == $id){
$slug = $category->slug;
}
}
return preg_replace("/value=\"(\d*)\"/", "value=\"$slug\"", $option[0]);
}
$select = wp_dropdown_categories("show_option_none=Category&hierarchical=1&hide_empty=0&echo=0");
$select = preg_replace_callback("#<option[^>]*>[^<]*</option>#", "replace_id_for_slug", $select);
echo $select; ?>
preg_match('/value="(\d*)"/', $option[0], $matches);
$id = $matches[1]; //problem on this line!
You didn't check whether anything was matched. If there was no match, then $matches[1]
does not exist. Fairly self-explanatory!
I'd suggest something like:
function replace_id_for_slug($option) {
$categories = get_categories("hide_empty=0");
preg_match('/value="(\d*)"/', $option[0], $matches);
if (!$matches) {
// return as if $id is empty if no match
return preg_replace('/value="(\d*)"/', 'value=""', $option[0]);
}
$id = $matches[1];
$slug = "";
foreach ($categories as $category) {
if ($category->cat_ID == $id) {
$slug = $category->slug;
}
}
return preg_replace('/value="(\d*)"/', 'value="' . $slug . '"', $option[0]);
}
What's really happening is that the Wordpress authors are really lazy, and instead of writing the above fix, they allowed PHP to just ignore this issue with a E_NOTICE
. You are seeing it because their "debug mode" is turning on certain error-reporting features.