Displaying Custom Fields in Your Templates

Contents

Displaying Custom Fields in Your Templates

Custom fields are a powerful feature in content management systems—particularly in WordPress—that let you attach arbitrary metadata to posts, pages or custom post types. In this article, you’ll learn how to store, retrieve and display custom field data in your theme templates.

1. What Are Custom Fields

Custom fields, sometimes called post metadata, allow developers and authors to extend content with extra data:

  • Product prices, SKU or stock status
  • Review scores and ratings
  • Event dates and locations
  • Any arbitrary key-value pair

2. Adding Custom Fields

You can add custom fields in various ways:

  • Via the default WordPress UI (“Custom Fields” meta box)
  • Programmatically with add_post_meta() or update_post_meta()
  • Using plugins like Advanced Custom Fields (ACF)

Example: Programmatic Addition

ltphp
post_id = 42
add_post_meta(post_id, price, 19.99, true)
update_post_meta(post_id, price, 24.99)
gt
    

3. Retrieving Custom Fields

The core function is get_post_meta():

Function Description
get_post_meta(id, key, true) Returns a single value
get_post_meta(id) Returns all meta as an array

4. Displaying in Templates

Place your code within the Loop or pass a post ID to retrieve data outside the Loop. Example:

Example: Within the Loop

ltphp if ( have_posts() ) : while ( have_posts() ) : the_post() gt
lth2gtltphp the_title() gtlt/h2gt

ltphp
price = get_post_meta( get_the_ID(), price, true )
if ( price ) {
echo ltp style=font-weight:boldgtPrice:



Acepto donaciones de BAT's mediante el navegador Brave :)



Leave a Reply

Your email address will not be published. Required fields are marked *