add_meta() WordPress Function

The add_meta() function is used to add meta data to a post. The first parameter is the post ID, the second parameter is the meta key, and the third parameter is the meta value. The fourth parameter is an optional boolean value that can be used to specify whether the meta data should be added to the post or not.

add_meta( int $post_ID ) #

Adds post meta data defined in the $_POST superglobal for a post with given ID.


Parameters

$post_ID

(int)(Required)


Top ↑

Return

(int|bool)


Top ↑

More Information

  • The information used is POSTed from the “Custom Fields” form on the Edit Post Administration screen.
  • Data used for the added metadata is taken from $_POST['metakeyselect'], $_POST['metakeyinput'], $_POST['metavalue']. Either the select or input fields are used for the meta key. If both are present, input field is used.

Top ↑

Source

File: wp-admin/includes/post.php

function add_meta( $post_ID ) {
	$post_ID = (int) $post_ID;

	$metakeyselect = isset( $_POST['metakeyselect'] ) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
	$metakeyinput  = isset( $_POST['metakeyinput'] ) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
	$metavalue     = isset( $_POST['metavalue'] ) ? $_POST['metavalue'] : '';
	if ( is_string( $metavalue ) ) {
		$metavalue = trim( $metavalue );
	}

	if ( ( ( '#NONE#' !== $metakeyselect ) && ! empty( $metakeyselect ) ) || ! empty( $metakeyinput ) ) {
		/*
		 * We have a key/value pair. If both the select and the input
		 * for the key have data, the input takes precedence.
		 */
		if ( '#NONE#' !== $metakeyselect ) {
			$metakey = $metakeyselect;
		}

		if ( $metakeyinput ) {
			$metakey = $metakeyinput; // Default.
		}

		if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) ) {
			return false;
		}

		$metakey = wp_slash( $metakey );

		return add_post_meta( $post_ID, $metakey, $metavalue );
	}

	return false;
}


Top ↑

Changelog

Changelog
VersionDescription
1.2.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More