Snippets

Joey Hernandez WordPress - Get Meta

Created by Joey Hernandez last modified
1
2
3
4
5
6
7
<?php
/**
 * usage
 */
$all_meta = get_meta( get_the_ID() );

$meta_value = ( array_key_exists( 'meta_name', $all_meta ) && $all_meta['meta_name'] != '' ) ? $all_meta['meta_name'] : '';
<?php
/**
 * Get Meta
 *
 * Utility function used to consolidate the quering of multiple meta values
 * for the given object.
 *
 * @param int	 	$id ID of the current object.
 * @param mixed		$fields Array/string containing meta field(s) to retrieve from database.
 * @param string	$type Type of metadata request. Options: post/term/user
 * @param constant	$output pre-defined constant for return type (OBJECT/ARRAY_A)
 *
 * @return mixed	MySQL object/Associative Array containing returned post metadata.
 */
function get_meta( $id = null, $fields = array(), $type = 'post', $output = ARRAY_A ) {
	global $wpdb;

	$fields		= esc_sql( $fields );
	$values_arr	= array();
	$values_obj	= new stdClass();
	$dbtable	= $wpdb->{$type.'meta'};
	$column_id	= $type . '_id';
	$id			= $id == null ? get_the_ID() : $id ;

	$query		= "SELECT meta_key, meta_value FROM {$dbtable} WHERE {$column_id} = {$id}";

	if ( !empty( $fields ) ) {

		if ( is_array( $fields ) ) {
			$query .= " AND meta_key IN ('". implode("','", $fields) ."')";
		} else {
			$query .= " AND meta_key = '{$fields}'";
		}
	}

	$results	=  $wpdb->get_results( $query, OBJECT_K );


	foreach ( $results as $key => $result ) {
		$values_arr[$key]	= $result->meta_value;
		$values_obj->{$key}	= $result->meta_value;
	}

	if ( !is_array( $fields ) && !empty( $values_arr[$fields] ) ) {

		return $output == ARRAY_A ? $values_arr[$fields] : $values_obj[$fields];

	}

	return $output == ARRAY_A ? $values_arr : $values_obj;
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.