Get values of a custom field belonging to the category or tag posts in Wordpress

This is an example how to get the values of a custom field belonging to the category or tag posts in WordPress:

<?php
function get_custom_field_values($custom_field,$term_id){
global $wpdb;

$query = “SELECT “.$wpdb->prefix.”postmeta.meta_value FROM “.$wpdb->prefix.”postmeta JOIN “.$wpdb->prefix.”term_relationships ON “.$wpdb->prefix.”term_relationships.object_id = “.$wpdb->prefix.”postmeta.post_id JOIN “.$wpdb->prefix.”term_taxonomy ON “.$wpdb->prefix.”term_relationships.term_taxonomy_id = “.$wpdb->prefix.”term_taxonomy.term_taxonomy_id AND “.$wpdb->prefix.”term_taxonomy.term_id='”.$term_id.”‘ WHERE meta_key = ‘”.$custom_field.”‘ GROUP BY “.$wpdb->prefix.”postmeta.meta_value;”;

return $wpdb->get_results($query);
}

$custom_field = “Brand”; //Custom field name
$term_id = 7; //Category or tag ID

$custom_field_values = get_custom_field_values($custom_field,$term_id);
?>

Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: