【问题标题】:WordPress update_post_meta values. Delete when empty or just test for ""?WordPress update_post_meta 值。空时删除还是只测试“”?
【发布时间】:2010-03-12 16:55:15
【问题描述】:

我下面的函数将从我的自定义元字段中获取值(在帖子被编辑,并单击保存或发布后)并更新或插入发布的元值。

但是,如果用户将此字段留空,我相信我想完全删除元数据(这样我就可以测试它的存在并相应地显示,而不是只检查“”)。

例如,我的一个元选项使用户能够为他们的帖子添加自定义标题,当该标题出现时,将填充页面的标签。但是,如果该字段为空,我想将标签默认为 the_title(),这只是用于标识页面/帖子的帖子标题。

由于我没有在保存时删除元数据,因此它总是在用户第一次在其中输入内容后出现,get_post_meta($post->ID,'MyCustomTitle', true) 总是正确的。此外,他们无法通过清除标题字段并点击发布来将其空白。

当用户清除字段时,为了将值清除为“”,我在保存中遗漏了什么?

if ($_POST['MyCustomTitle']) {
update_custom_meta($postID, $_POST['MyCustomTitle'], 'MyCustomTitle');
}

function update_custom_meta($postID, $newvalue, $field_name) {
// To create new meta
if(!get_post_meta($postID, $field_name)){
add_post_meta($postID, $field_name, $newvalue);
}else{
// or to update existing meta
update_post_meta($postID, $field_name, $newvalue);
}
}

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    类似的东西呢

    $customTitle = $_POST['MyCustomTitle'];
    if ($customTitle<>"") {
        update_custom_meta($postID, $customTitle, 'MyCustomTitle');
    }else{
        $customTitle = "";
        update_custom_meta($postID, $customTitle, 'MyCustomTitle');
    }
    

    获取您的帖子值,分配给变量“$customTitle” 如果它不是空的,那么用新值更新,或者只是用空白值更新它?

    【讨论】:

    • 如果留空,最好从帖子中删除元值 - 否则数据库可能会充满空白元数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多