Custom fields won't update

时间:2011-10-31 作者:Ciprian

我对自定义字段有一个小问题。这就是我想做的:

每当添加新帖子时,我都会检查所选类别,抓取子类别,并根据子类别创建值为“0”的自定义字段checked="yes" 至复选框一切都很好。我面临的唯一问题是多个单词的自定义字段。例如,“Firefox”可以工作,但如果自定义字段为“Firefox Browser”,则不会更新。如果我手动编辑帖子并将“1”添加到“Firefox Browser”自定义字段,则选中该复选框,我的div将显示“Firefox Browser”标题。取消选中复选框并点击提交会将值更改为“0”,但选中复选框不会将值更改为“1”。

有人知道为什么会这样吗?

非常感谢。

这是我的代码:

<?php
 //Get the first category of the post
$post_category = get_the_category();
$args = array(\'parent\' => $post_category[0]->cat_ID, \'hide_empty\' => 0);
$categories = get_categories( $args );  

<form action="http://mysite.com/checkform" method="post">


foreach($categories as $category) {
$chkchk = get_post_meta($post->ID, $category->name, true);
if ($chkchk != "0"){$i = \'checked="yes"\';}else{$i = "";}
echo \'<input type="checkbox"\' . $i . \'name=\'.\'"\'.$category->name.\'"\'.\'value=""  />\'.$category->name;

}

<input type="hidden" name="post_id" value="<?php echo $post->ID; ?>">
<input type="hidden" name="post_cat" value="<?php echo $post_category[0]- >cat_ID; ?>">
<input type="submit" value="Submit" />
</form>
?>
<小时>
<?php
 //Get hidden
$post_id = $_POST[\'post_id\'];
$post_cat = $_POST[\'post_cat\'];


 //Get current custom field values
$post_catt = get_the_category();
$args = array(\'parent\' => $post_cat, \'hide_empty\' => 0);
$cats = get_categories( $args
);


foreach($cats as $cat) {
$checkthis = get_post_meta($post_id, $cat->name, true);

if (isset($_POST[$cat->name])) {
if($checkthis != 1){
update_post_meta($post_id, $cat->name, 1);}
}else{
if($checkthis != 0);{
update_post_meta($post_id, $cat->name, 0);}
}}`
?>
<小时>
<?php
        foreach($categories as $category) {
                $dropthis = get_post_meta($post->ID, $category->name, true);
                //echo $category->name;
                //echo "=";
                //echo $dropthis;
                $abcd = str_replace (" ", "", $category->name);
                $cat_php = strtolower($abcd);
            if($dropthis != 0){
                include \'drops/\'.$cat_php.\'.php\';
            }

    } ?>

1 个回复
最合适的回答,由SO网友:kaiser 整理而成

\'name\' 是在post元数据中保存为键的内容,因此在保存之前,对类别名称进行str\\u替换:

// Wrong: name="My Category"
echo \'<input type="checkbox"\' . $i . \'name=\'.\'"\'.$category->name.\'"\'.\'value=""  />\'.$category->name;

// Right: name="my_category"
$name = str_replace( \' \', \'_\', strtolower( $category->name ) );
$checked = get_post_meta( ...etc... );
echo "<input type=\'checkbox\'{$i} name=\'{$name}\' value=\'{$checked}\'  />$name;

结束

相关推荐