为什么这个UPDATE_POST_META函数不删除定制字段本身?

时间:2016-12-22 作者:BlueDogRanch

我正在尝试使用复选框将meta key的值设置为“yes”或null,这样我就可以使用一个查询来选择帖子,该查询检查meta key是否存在,而不使用meta\\u key的值。我不想将meta\\u键添加到所有现有帖子中,并且希望在取消选中该meta\\u键时将其删除。

但是update_post_meta 此函数结束时,不会删除meta\\u键featured-checkbox 更新时。如何获取删除密钥的函数?

// Featured Post metabox

function prfx_featured_meta() {
    add_meta_box( \'prfx_meta\', __( \'Featured Posts\', \'prfx-textdomain\' ), \'prfx_meta_callback\', \'post\', \'side\', \'high\' );
}
add_action( \'add_meta_boxes\', \'prfx_featured_meta\' );

/**
 * Outputs the content of the meta box
 */

function prfx_meta_callback( $post ) {
    wp_nonce_field( basename( __FILE__ ), \'prfx_nonce\' );
    $prfx_stored_meta = get_post_meta( $post->ID );
    ?>

 <p>
    <span class="prfx-row-title"><?php _e( \'Check if this is a featured post: \', \'prfx-textdomain\' )?></span>
    <div class="prfx-row-content">
        <label for="featured-checkbox">
            <input type="checkbox" name="featured-checkbox" id="featured-checkbox" value="yes" <?php if ( isset ( $prfx_stored_meta[\'featured-checkbox\'] ) ) checked( $prfx_stored_meta[\'featured-checkbox\'][0], \'yes\' ); ?> />
            <?php _e( \'Featured Item\', \'prfx-textdomain\' )?>
        </label>

    </div>
</p>   

    <?php
}

/**
 * Saves the custom meta input
 */
function prfx_meta_save( $post_id ) {

    // Checks save status
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ \'prfx_nonce\' ] ) && wp_verify_nonce( $_POST[ \'prfx_nonce\' ], basename( __FILE__ ) ) ) ? \'true\' : \'false\';

    // Exits script depending on save status
    if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
        return;
    }

    // Checks for input and sanitizes/saves if needed
    // How do I delete the featured-checkbox key and not update it?
    if( isset( $_POST[ \'featured-checkbox\' ] ) ) {
        update_post_meta( $post_id, \'featured-checkbox\', sanitize_text_field( $_POST[ \'featured-checkbox\' ] ) );
    }

}
add_action( \'save_post\', \'prfx_meta_save\' );

Update 12/22/16: this change works:

// Checks for input and saves - save checked as yes or deletes meta_key if no
if( isset( $_POST[ \'featured-checkbox\' ] ) ) {
    update_post_meta( $post_id, \'featured-checkbox\', \'yes\' );
} else {
        delete_post_meta( $post_id, \'featured-checkbox\' );
}

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

你在寻找delete_post_meta($post_id, $meta_key, $meta_value);

参数

$post_id (整数)(必填)要从中删除字段的帖子的ID。默认值:无

$meta_key (string)(必选)要删除的字段的键。默认值:无

$meta_value (混合)(可选)要删除的字段的值。这用于使用samekey区分多个字段。如果留空,将删除具有给定键的所有字段。默认值:空