We can add some custom fields for our posts in wordpress. How to get values of these fields? In this tutorial, we will introduce you how to do using some simple examples.
We can use wordpress get_post_meta() to implement it.
Syntax
get_post_meta( int $post_id, string $key = '', bool $single = false )
Retrieves a post meta field for the given post ID.
$post_id: (Required) the post id
$key: (Optional) the custom field name, such as is_run, tutorial_page.
$single: (Optional) ) If true, returns only the first value for the specified meta key. This parameter has no effect if $key is not specified.
Get a specified custom filed value
For example, if we want to get the value of the custom field “url” in post 13, we can do like this:
$vx = get_post_meta(13, "url", true); print($vx) if($vx != ''){ }
Then you will get its value: https://www.tutorialexample.com/
In this code, we have set $single = true, it will return only the first value. However, if we set $single = false.
$vx = get_post_meta(13, "url", false); print($vx) if($vx != ''){}
The $vx will be:
Array ( [0] => https://www.tutorialexample.com/ )
The value of $vx is a php array.
Get all custom fields value of a post
We also can get all custom fields value of a post. Here is an example:
$vx = get_post_meta(13); print_r($vx);
Run this code, you will get this result.
Array ( [_edit_lock] => Array ( [0] => 1590453347:1 ) [_basic_liao_good_rate] => Array ( [0] => field_5ecb9135575aa ) [basic_liao_health_rate] => Array ( [0] => 0 ) [_basic_liao_health_rate] => Array ( [0] => field_5ecbb72c26553 ) [basic_liao_bad_rate] => Array ( [0] => 0 ) [_basic_liao_bad_rate] => Array ( [0] => field_5ecb90e5575a9 ) [basic_liao_repeat_reate] => Array ( [0] => 0 ) [_basic_liao_repeat_reate] => Array ( [0] => field_5ecb9176575ab ) [basic_liao] => Array ( [0] => ) [_improve_liao_improve_good_rate] => Array ( [0] => field_5ecb92f97ba18 ) [improve_liao_improve_health_rate] => Array ( [0] => 0 ) [_improve_liao_improve_health_rate] => Array ( [0] => field_5ecbb7a126555 ) [improve_liao_improve_bad_rate] => Array ( [0] => 0 ) [_improve_liao_improve_bad_rate] => Array ( [0] => field_5ecb93277ba19 ) [improve_liao_improve_repeat_rate] => Array ( [0] => 0 ) [_improve_liao_good_desc] => Array ( [0] => field_5ecbbfe6d745d ) [improve_liao] => Array ( [0] => ) [_improve_liao] => Array ( [0] => field_5ecb92aa7ba16 ) )
You will find all custom field value is php array object.