get_post_meta() – Function description, parameters and basic usage

Description:

get_post_meta Returns the value of the selected Custom Field. It is very useful for advanced custom functionalities(like post thumbnails, sorting data by custom fields, adding additional info in posts etc.).

Parameters:

$post_id (required) -The id of the post which custom field you want the custom field from

$key (required) – The name(slug or meta value) of the custom field

$single (optional) – If you want to return a single result set it to true and the function will return a string of the needed data. If you set it to false(or don`t set it at all) it will return an array

Basic usage:

$custom_field = get_post_meta( $post->ID );

//$key and $single parameters are not set so it returns an associative array of all the custom fields

//The array structure will be similar to the following:

Array
(
     [_edit_last] => Array
     (
         [0] => 1
     )

     [Test custom field] => Array
     (
         [0] => Test description
     )

    [Test custom field 1] => Array
     (
         [0] => Test description 1
    )

    [related] => Array
    (
         [0] =>
     )

    [_wp_page_template] => Array
    (
        [0] => test-page.php
     )

    [_edit_lock] => Array
     (
         [0] => 1348144348:1 
     )

    [description] => Array
    (
         [0] =>
    )

    [parameters] => Array
     (
         [0] =>
    )

)

 

Example of usage of get_post_meta with $key and value set:

$meta = get_post_meta( $post->ID, “Test custom field”, true );
echo $meta;
//Returns a string with the meta_value. In this case “Test description”

One of the more advanced examples of using Custom Fields(and the most popular respectively) is creating post thumbnails. Create a custom field called thumb with value the link to your image.

if ( get_post_meta($post->ID, 'thumbnail', true) )
{
    echo ''.the_title().'';
}
About Pavel Petrov 2 Articles |  21 How-tos
Pavel is a senior developer for the last 7 years, with extended interest in Linux administration, WordPress and Symfony.

Be the first to comment

Leave a Reply

Your email address will not be published.


*