This article shows a piece of PHP code that query all Custom Fields (extra fields or meta data) of a particular post instead of hitting the WordPress database for every custom field.
Assume that you’ve added a lot of custom fields or extra fields for each of post, pulling all meta data in one request will reduce connections to the database and will significant improve your WordPress website performance.
1. PHP Get All Custom Fields For A Single Post In WordPress
The PHP script below will query and store all custom fields for the current post in an Array. And then we can easily read value of these custom fields such as featured_image, demonstration_url, download_url, etc.
<?php $post_id = $post->ID; global $wpdb; $post_meta_data = array(); $wpdb->query(" SELECT `meta_key`, `meta_value` FROM $wpdb->postmeta WHERE `post_id` = $post_id "); foreach($wpdb->last_result as $k => $v){ $post_meta_data[$v->meta_key] = $v->meta_value; }; $featured_image = $post_meta_data["featured_image"]; $disable_meta = $post_meta_data["disable_meta"]; $center_ads = $post_meta_data["center_ads"]; $demonstration_url = $post_meta_data["demonstration_url"]; $download_url = $post_meta_data["download_url"]; ?> |
You can place this PHP script right in the loop-single.php file in your WordPress template folder or create a function that returns all custom field for a single post then place it in your WordPress functions.php file as below:
2. Function returns all custom field in WordPress
<?php function get_all_post_custom_fields($post_id){ global $wpdb; $post_meta_data = array(); $wpdb->query(" SELECT `meta_key`, `meta_value` FROM $wpdb->postmeta WHERE `post_id` = $post_id "); foreach($wpdb->last_result as $k => $v){ $post_meta_data[$v->meta_key] = $v->meta_value; }; return $post_meta_data; } ?> |