How to Add One Custom Field for Many Posts in WordPress

3 from 5
from 10 user
(Rate this post)
How to Add One Custom Field for Many Posts in WordPress

Use this code snippet to add the same meta data value for multiple WordPress posts at once. Here I provided solutions that save one custom field in many posts.

I recently encountered a situation requiring adding one custom field in multiple WordPress posts simultaneously.

So, I developed a solution that inserts the same meta data for multiple posts.

At this time, I am sharing my code with you here.

Solutions to Add the Same Custom Field for Multiple Posts

If you want to add the same meta data for many posts when developing WordPress, You have two options:

  • The first option, with better performance, uses a single database query to add multiple records to the WordPress postmeta table.
  • The second option iterates posts and uses add_posts_meta for each item separately.

1- Add one custom field for multiple posts with a single query

Using a single SQL query, this new custom function simultaneously adds multiple meta data for all post ids.

function add_multiple_posts_meta( $post_ids, $meta_key, $meta_value, $unique = false ){

	// if meta key or post ids are not set, do not continue
	if( !$meta_key || !absint( $post_ids ) ){
		return false;
	}

	//fallback to WordPress default add_post_meta if single post id passed
	if( is_numeric( $post_ids ) || ( is_array( $post_ids ) && count( $post_ids ) == 1 ) ){
		return add_post_meta(
			is_array( $post_ids ) ? $post_ids[ 0 ] : $post_ids,
			$meta_key,
			$meta_value,
			$unique
		);
	}

	global $wpdb;

	$valid_post_ids = array_unique(
		array_filter( $post_ids, function( $post_id ) use ( $wpdb, $meta_key, $unique ){
			//check if the post id exists
			return $post_id &&
				is_numeric( $post_id ) &&
				get_post_status( $post_id ) &&
				(
					!$unique ||
					$wpdb->get_var( $wpdb->prepare(
						"SELECT COUNT(*) FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s",
						$meta_key,
						$post_id )
					)
				);
		} )
	);

	//if all post ids had problem, there is no reason to continue
	if( !count( $valid_post_ids ) ){
		return false;
	}

	//sanitize meta key & value
	$meta_key   = wp_unslash( $meta_key );
	$meta_value = sanitize_meta( wp_unslash( $meta_value ), $meta_value, 'post' );

	//create an array of data to be inserted
	$insert_data    = array();
	$insert_formats = array();

	foreach( $valid_post_ids as $post_id ){
		//insert id, key, value in data array (order is important)
		array_push( $insert_data, $post_id, $meta_key, $meta_value );

		//we have one format for all records
		$insert_formats[] = '(%d, %s, %s)';
	}

	//query string with (%d, %s, %s) as value
	$sql_string = "INSERT INTO $wpdb->postmeta (`post_id`, `meta_key`, `meta_value`) VALUES "
		. implode( ', ', $insert_formats );

	//replace (%d, %s, %s) with actual data
	$sql_query = $wpdb->prepare( $sql_string, $insert_data );

	//returns true if succeeded, otherwise false
	return $wpdb->query( $sql_query );

}

It should be noted you better check if this function exists before declaring it.

To do this, our new function will wrap inside an if condition like the below:

if( !function_exists( 'add_multiple_posts_meta' ) ){
    copy above codes here...
}

Do the same when defining a custom WordPress function to avoid future conflicts.

If third-party plugins define this custom function with same name or the WP team decides to add it in the future, You’ll get a PHP error that says this function was defined before.

How to use this custom function

The add_multiple_posts_meta function works with an array of post IDs. Then, I defined an array of 1, 2, 3 post IDs to set a meta value for:

$post_ids = array( 1, 2, 3 );
$meta_key = 'your_meta_key';
$meta_value = 'your desired value';
$dont_add_if_key_exists = false;
add_multiple_posts_meta( $post_ids, $meta_key, $meta_value, $dont_add_if_key_exists );

Explain for this custom function

Our new add_multiple_posts_meta function has a similar syntax to the add_post_meta in WordPress.

The only difference is this function accepts an array of post IDs or a single post ID if you wish.

As a result, It falls back to add_post_meta if you pass a single post ID to it (integer or array with one element).

See your second option if you want core WordPress functions to handle this situation.

2- Iterate post IDs to add the custom field for each post

This solution is easy because you can use add_post_meta and leave it all to this function.

$post_ids = array( 1, 2, 3 );
$meta_key = 'your_meta_key';
$meta_value = 'your desired value';
$dont_add_if_key_exists = false;

foreach( $post_ids as $post_id ){
	add_post_meta( $post_id, $meta_key, $meta_value, $dont_add_if_key_exists );
}

The add_post_meta is responsible for adding a single custom field for one post, and it does not support adding meta data to multiple post items.

Thus, you have no choice but to use a PHP loop (foreach, for, while, do while) to iterate an array of post IDs. Then using add_post_meta on each one of IDs you have in that array.

To make this solution work, I used PHP’s foreach loop to add meta data for every post ID stored in the $post_ids array.

More Information on WordPress Custom Fields

WordPress custom fields hold all the extra information you need to add features to your WordPress website.

Whether you’re looking for a way to store post view numbers, filterable keyword tags, or other extra content pieces, custom fields are a great way to do it.

Fortunately, many sources are available online to learn more about custom fields and how they work in WordPress.

Resources for developing WordPress custom fields

First, The WordPress official website is an excellent place to start, providing detailed information about how the posts work and how meta data can be added or modified.

Second, StackOverflow contains many questions about WordPress’s custom fields feature and related topics.

Last, you may also want to read my tutorial on managing WordPress custom fields through the admin panel or using PHP codes.

With the right guidance from these sources, one can easily use this useful feature in your WordPress site to make it feature-rich.

What do you think about "How to Add One Custom Field for Many Posts in WordPress"?

Your rating submit was successfull.

Your rating submit was not successfull.

Menu