delete_field()

Description

This function is used to delete a field value from a specific post.

Parameters

<?php delete_field($selector, $post_id); ?>
  • $selector (string) the field name or key (required)
  • $post_id (mixed) Specific post ID where your value was entered. Defaults to current post ID (not required). This can also be options / taxonomies / users / etc

Usage

Basic (field name)

This example demonstrates how to delete the value of a field called ‘test’ on the current post being viewed.

<?php

// delete
delete_field('test');
    
?>

Basic (field key)

This example demonstrates how to achieve the same as above using the field’s key instead of it’s name.

<?php

// delete
delete_field('field_123456');
    
?>

Advanced

This example will demonstrate how load all posts that contain a custom field (called ‘color’) and delete the value from each post. Note that the foreach loop uses a variable called $p instead of $post to avoid any collisions with the global $post object.

<?php 

// get posts
$posts = get_posts(array(
	'post_type'			=> 'post',
	'posts_per_page'	=> -1,
	'meta_key' 			=> 'color'
));


// check
if( $posts ) {
	
	// loop
	foreach( $posts as $p ) {
		
		// delete
		delete_field('color', $p->ID);
		
	}
	
}

?>

Related

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.