Khalil Ghâñmî

0 %
Khalil Ghâñmî
Développeur full-stack
  • Residence:
    Tunis
  • City:
    Bardo
  • Age:
    30
French
English
arabe
  • HTML 5 / CSS 3
  • Bootstrap
  • JavaScript / Jquery/Ajax
  • ReactJS
  • API
  • Angular
  • PHP/Mysql
  • Python
  • Java
  • Wordpress
  • OpenCart
  • Illustrator | Photoshop | Premier Pro | Animate
  • OVH | Godaddy | Vipdomaine | Zenhosting | LWS | Hostgator
  • Cpanel
  • Google Search | Google sheets | Google docs | Office

Display custom fields with get_post_meta()

30 August 2022

The get_post_meta() function allows you to be more precise and target the field to retrieve.

<?php get_post_meta($post_id, $key, $unique); ?>
  • $post_id: Accepts the post id.
  • $key: accepts the name of the custom field.
  • $unique: accepts true or false. If true, the function returns a simple result as a string. By default the value is false and returns an array.

If only $post_id is present, the function returns an array with all custom fields for the relevant post, in array form.

Example

For an article whose id is 8 and whose custom field is named “mood”, with the value “content”, the function to insert in the page templates to retrieve the value “content” is:

humeur : <?php echo get_post_meta('8','humeur',true); ?> 

To display this same value, inside a loop the code will be as follows:

<?php 
$humeur = get_post_meta( get_the_ID(), 'humeur', true ); 
if ( ! empty( $humeur ) ) { 
    echo $humeur; 
} 
?> 

To retrieve the URL of an image assigned to a “thumb” field…

Posted in Non classé, PHPTags:
Write a comment