Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

i have done this many times but not via a form so i am getting a weird issues when trying to assign a "selected" based on the current post term id...

Maybe the use of get_the_category and then get_categories creates a conflict? Any one has any idea as to why this might happen?

No matter what the selected item is the last one and not the Current post (get the post id via an outside form) category

Here is my code:

<?php 
$postId = $_POST['postid']; // the value is recieved properly
$currentCategory = get_the_category($postId);  // the value is recieved properly
$currentCategoryId = $currentCategory[0]->term_id; // the value is assigned properly

$categories = get_categories('hide_empty=0'); // the value is recieved properly
$optionname = "postcats"; // the value is recieved properly
$emptyvalue = "";

// SELECET DROP DOWN TERMS
echo '<select name="'.$optionname.'" class="clientList"><option selected="'.$selected.'" value="'.$emptyvalue.'">'.__('Choose a category','sagive').'</option>';
foreach($categories as $category){
    // next line seem to not work!
    if($currentCategoryId == $category->term_id) {$selected = 'selected="selected"';}
    echo '<option name="'.$category->term_id.'" value="'.$category->term_id.'" '.$selected.'>'.$category->name.'</option>';
}

echo '</select>';
?>

.
if i try to echo the $currentCategoryId outside the foreach it works
but not inside it.. kinda wierd!

Your help would me most appreciated.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

OMG - i falied to clean "$selected" value... hope this helps someone
if you get confused for a moment like i did

<?php 
$postId = $_POST['postid']; // the value is recieved properly
$currentCategory = get_the_category($postId);  // the value is recieved properly
$currentCategoryId = $currentCategory[0]->term_id; // the value is assigned properly

$categories = get_categories('hide_empty=0'); // the value is recieved properly
$optionname = "postcats"; // the value is recieved properly
$emptyvalue = "";

// SELECET DROP DOWN TERMS
echo '<select name="'.$optionname.'" class="clientList"><option selected="'.$selected.'" value="'.$emptyvalue.'">'.__('Choose a category','sagive').'</option>';
foreach($categories as $category){

    // HERE I ENTERED AN ELSE THAT WOULD CLEAN
    // THE VALUE OF $SELECTED

    if($currentCategoryId == $category->term_id) {$selected = 'selected="selected"';} else {$selected = ''}
    echo '<option name="'.$category->term_id.'" value="'.$category->term_id.'" '.$selected.'>'.$category->name.'</option>';
}

echo '</select>';
?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.